程序员面试金典--面试24之二叉树和为某一值的路径

题目描述

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

思路: 
  •      递归先序遍历树, 把结点加入路径。
  •      若该结点是叶子结点则比较当前路径和是否等于期待和。是的话打印从根节点到叶子节点的路径。
  •     弹出结点,每一轮递归返回到父结点时,当前路径也应该回退一个结点

树的定义:
struct TreeNode
{
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x):val(x),left(NULL),right(NULL) { }
};

实现代码:(注释的代码是单纯的打印出路径,牛客网上的题是要保存路径)
#include<iostream>
using namespace std;
#include<vector>

struct TreeNode
{
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x):val(x),left(NULL),right(NULL) { }
};


/*
void Print(TreeNode *root,vector<int>&v,int &curNumber,int expectNumber)
{
	if(root == NULL)
		return ;
	curNumber += root->val;
	v.push_back(root->val);
	bool isLeaf = (root->left == NULL && root->right == NULL);
	if(curNumber == expectNumber && isLeaf)
	{
		for(int i = 0; i < v.size(); ++i)
		{
			cout << v[i] << " ";
		}
		cout <<endl;
	}

	if(root->left)
		Print(root->left,v,curNumber,expectNumber);
	if(root->right)
		Print(root->right,v,curNumber,expectNumber);

	curNumber -= root->val;
	v.pop_back();
}




void  FindPath(TreeNode *root,int expectNumber)
{
	vector<int> v;
	
	int curNumber = 0;
	
	Print(root,v,curNumber,expectNumber);


}

*/


void FindPath(TreeNode *root,int expectNumber,int &curNumber,vector<int> &v, vector<vector<int> > &ret)
{
	if(root == NULL)
		return ;
	curNumber += root->val;
	v.push_back(root->val);
	bool isLeaf = (root->left == NULL && root->right == NULL);
	if(curNumber == expectNumber && isLeaf)
	{
		ret.push_back(v);
	}

	if(root->left)
		FindPath(root->left,expectNumber,curNumber,v,ret);
	if(root->right)
		FindPath(root->right,expectNumber,curNumber,v,ret);

	curNumber -= root->val;
	v.pop_back();
}




vector<vector<int> >   FindPath(TreeNode *root,int expectNumber)
{

	vector< vector<int> > ret ;
	vector<int>v;
	int cursum = 0;
	FindPath(root,expectNumber,cursum,v,ret);
	return ret;
}
void test()
{
	TreeNode *p1 = new TreeNode(10);
	TreeNode *p2 = new TreeNode(5);
	TreeNode *p3 = new TreeNode(12);
	TreeNode *p4 = new TreeNode(4);
	TreeNode *p5 = new TreeNode(7);

	p1->left = p2;
	p1->right = p3;
	p2->left = p4;
	p2->right = p5;

	vector<vector<int> > ret = FindPath(p1,22);
	for(int i = 0; i < ret.size(); ++i)
	{
		for(int j = 0; j< ret[i].size(); ++j)
			cout << ret[i][j] << " ";
		cout <<endl;
	}
}

int main()
{
	test();

	cout << "hello ...."<<endl;

	return 0;
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值