剑指offer之二叉树路径求和

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

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值