在二叉树中找出和为某一值的所有路径
#include <iostream>
#include <assert.h>
#include "btree.h"
void printPath(int* path, int size)
{
for (int i = 0; i < size; ++i)
std::cout << path[i] << " ";
std::cout << std::endl;
}
void findPath(const TNode* root, int sum, int path[], int top)
{
assert(root);
path[top ++] = root->_data;
sum -= root->_data;
if (root->_left == NULL && root->_right == NULL)
{
if (sum == 0)
printPath(path, top);
}
else
{
if (root->_left != NULL)
findPath(root->_left, sum, path, top);
if (root->_right != NULL)
findPath(root->_right, sum, path, top);
}
--top;
sum += root->_data;
}
void printPaths(const TNode* root, int treeHeight, int sum)
{
int *path = new int[treeHeight];
findPath(root, sum, path, 0);
delete [] path;
path = NULL;
}
int main()
{
int array[] = {15,9,17,5,11,4,6};
int size = sizeof(array) / sizeof(array[0]);
BTree tree;
tree.createTree(array, size);
int treeHeight = tree.height();
std::cout << treeHeight << std::endl;
printPaths(tree.root(), treeHeight, 35); // 寻找和为35的二叉树路径
return 0;
}
本人觉的这个算法很巧妙,不是通过加和的方式,而是减值的方式,当减为0时,即是要找的路径,并且路径通过一个数组就记录的方式也非常方便和简单!