二叉树中和为某一值的路径

#include <iostream>
#include <vector>  
using namespace std;  
  
struct node{
    int data;
    node* lchild;
    node* rchild;
};

void find_path(node* r, int exceptedSum, vector<int> &path,
                    int& curSum);
                    
node* buildBTree(int* a, int &i)
{
    if(a==NULL || a[i]==-1)
        return NULL;
    node* p = new node;
    p->data = a[i];
    p->lchild = buildBTree(a, ++i);
    p->rchild = buildBTree(a, ++i);
    return p;
}

void preOrder(node* r)
{
    if(r!=NULL)
    {
        cout<<r->data<<" ";
        preOrder(r->lchild);
        preOrder(r->rchild);
    }else{
        cout<<-1<<" ";
    }
}

node* buildBTree()
{
    int a[] = {10, 5, 4, -1, -1, 7, -1, -1, 12, -1, -1};
    int i=0;
    return buildBTree(a, i);
}

void find_path(node* r, int exceptedSum)
{
    if(r==NULL)
        return ;
    vector<int> path;
    int curSum = 0;
    find_path(r, exceptedSum, path, curSum);
}

void find_path(node* r, int exceptedSum, vector<int> &path,
                    int& curSum)
{
    curSum += r->data;
    path.push_back(r->data);

    if(curSum==exceptedSum && r->lchild==NULL && r->rchild==NULL)
    {
        cout<<"a path is found: ";
        vector<int>::iterator iter = path.begin();
        for(; iter != path.end(); iter++)
            cout<<*iter<<" ";
        cout<<endl;
    }
    
    if(r->lchild != NULL)
        find_path(r->lchild, exceptedSum, path, curSum);
    if(r->rchild != NULL)
        find_path(r->rchild, exceptedSum, path, curSum);
    
    curSum -= r->data;
    path.pop_back();
}                    

int main()  
{  
    node* r = buildBTree(); 
    find_path(r, 22);
    return 0;  
}  

上面的关键代码是抄剑指offer上的,如果自己写的话,我更容易写成下面的样子:

bool is_leaf(node* r)
{
	if(r==NULL || (r->lchild==NULL && r->rchild==NULL))
		return true;
	return false;
}

void find_path(node* r, int exceptedSum, vector<int> &path,
                    int& curSum)
{
   if(curSum+r->data < exceptedSum && !is_leaf(r))
   {
		curSum += r->data;
		path.push_back(r->data);
		if(r->lchild != NULL)
			find_path(r->lchild, exceptedSum, path, curSum);
		if(r->rchild != NULL)
			find_path(r->rchild, exceptedSum, path, curSum);
		curSum -= r->data;
		path.pop_back();
   }
   else if(curSum+r->data==exceptedSum && is_leaf(r))
   {
	   for(int i=0; i<path.size(); i++)
		   cout<<path[i]<<" ";
	   cout<<r->data<<endl;
   }
}      

剑指offer是节点不是页节点都要进行计算,我加了个限制条件“curSum+r->data < exceptedSum”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值