剑指offer 二叉树中和为某一值的所有路径

题目:
    输入一个整数和一棵二叉树。打印出和与输入整数相等的所有路径。
    路径指的是从树的根结点开始往下访问一直到叶结点的路径。
例子:
    例如输入整数22和如下二叉树
                                            10
                                           /   \
                                          5     12
                                        /   \   
                                      4     7 
则打印出两条路径:10, 1210, 5, 7。
思路:
    当访问到某一结点时,添加到路径上,并累加当前结点的值。                                                     
    如果当前结点不是叶结点,则继续访问它的子结点。当前结点访问结束后,递归函数回到父结点。                                
    访问完当前节点,返回时删除并减去当前结点的值,确保返回父结点时路径刚好是根到父结点的路径。

#include<iostream>
#include<vector>
using namespace std;
typedef struct Tree
{
    struct Tree* l;
    struct Tree* r;
    int val;
}tree;
void path(tree* root,int num,int& cur,vector<int>& v)
{
    if(root==NULL) return;
    cur+=root->val;
    v.push_back(root->val);
    int leaf=0;
    if((root->l==NULL) && (root->r==NULL)) leaf=1;
    if((leaf==1) &&(cur==num))
    {
        for(auto iter:v)
        {
            cout<<iter<<" ";
        }
        cout<<endl;
    }
    if(root->l) path(root->l,num,cur,v);
    if(root->r) path(root->r,num,cur,v);
    cur-=root->val;
    v.pop_back();
}
tree* creat_tree(int* a,int size,int& index)
{
    tree* root=new tree;
    if(index<size && a[index]=='#')
    {
        root=NULL;
    }
    if(index<size && a[index]!='#')
    {
        root->val=a[index];
        root->l=creat_tree(a,size,++index);
        root->r=creat_tree(a,size,++index);
    }
    return root;
}
int main()
{
    /*
    tree* root=new tree;
    tree* p10=new tree;
    tree* p11=new tree;
    tree* p20=new tree;
    tree* p21=new tree;
    root->l=p10;
    root->r=p11;
    root->l->l=p20;
    root->l->r=p21;
    root->val=10;
    p10->val=5;
    p11->val=12;
    p20->val=4;
    p21->val=7;
    p20->l=NULL;
    p20->r=NULL;
    p21->l=NULL;
    p21->r=NULL;
    p11->l=NULL;
    p11->r=NULL;  
    */
    int a[11]={10,5,4,'#','#',7,'#','#',12,'#','#'};
    int index=0;
    tree* root=creat_tree(a,11,index);
    int cur=0;
    vector<int> v;
    path(root,22,cur,v);
    return 0;
}

'''
输出:
10 5 7 
10 12 
'''
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值