剑指offer之二叉树路径求和

来源:互联网 发布:vb.net boolean 编辑:程序博客网 时间:2024/05/21 19:48

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);}

0 0
原创粉丝点击