1.题目
二叉树根节点到叶子节点的节点序列称为路径,如果路径上所有节点和为指定的某个数,就打印该路径
10
/
5 12
/
4 7
有两条路径上的结点和为22,分别是10+5+7和10+12
思路比较简单:先序遍历二叉树,并同步更新直到当前节点为止的sum和path,如果是叶子节点,与指定数比较,若相等,输出序列
2.代码
#include<stdio.h>
#include<vector>
struct BinaryTreeNode
{
int value;
BinaryTreeNode* left;
BinaryTreeNode* right;
};
void doFindPath(BinaryTreeNode* root, int expect, std::vector& path, int& current)
{//注意path和current是引用
current += root->value;//进入本节点,更新本节点对current和path的影响
path.push_back(root->value);//插入队尾
bool isLeaf = root->left==NULL && root->right==NULL;
if(isLeaf && current == expect)//打印结果
{
std::vector::iterator iter = path.begin();
while(iter != path.end())
{
printf("%d ", *iter);
iter ++;
}
printf("n");
}
if(root->left)
doFindPath(root->left, expect, path, current);
if(root->right)
doFindPath(root->right, expect, path, current);
current -= root->value;//返回父节点时,删除本节点造成的负面影响
path.pop_back();
}
void findPath(BinaryTreeNode* root, int expect)
{
if(root == NULL)
return;
std::vector path;
int current = 0;
doFindPath(root, expect, path, current);
}
最后
以上就是漂亮蜻蜓最近收集整理的关于剑指offer之二叉树路径求和的全部内容,更多相关剑指offer之二叉树路径求和内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复