C++二叉树路径搜索

问题

给定一个二叉树和一个int型数值target,判断是不是有一条从根到叶子的路径,加和等于target

思路

《剑指Offer》第34题:二叉树中和为某一值的路径。

当用前序遍历的方式访问到某一节点时,把该节点添加到路径上,并累加该节点的值。如果该节点为叶节点,并且路径中节点值的和刚好等于输入的整数,则当前路径符合要求,将其保存到结果vector中。如果当前节点不是叶节点,则继续访问它的子节点。当前节点访问结束后,递归函数将自动回到它的父节点。因此,在函数退出之前要在路径上删除当前节点并减去当前节点的值,以确保返回父节点时路径刚好是从根节点到父节点。
不难看出,保存路径的数据结构实际上是一个栈,因为路径要与递归调用状态一致,而递归调用的本质就是一个压栈和出栈的过程。

#include<iostream>
#include<vector>

using namespace std;

class BinaryTree
{
public:
	int val;
	BinaryTree *pL_tree;
	BinaryTree *pR_tree;

	BinaryTree(int x) :val(x), pL_tree(nullptr), pR_tree(nullptr){};
};

void FindPath(BinaryTree* pRoot, 
			  int expectedSum, 
			  std::vector<int>& path, 
			  int& currentSum,
			  vector<vector<int>> &ans)
{
	currentSum += pRoot->val;
	path.push_back(pRoot->val);

	bool isLeaf = (pRoot->pL_tree == nullptr) && (pRoot->pR_tree == nullptr);
	if (currentSum == expectedSum && isLeaf)
	{
		ans.push_back(path);
	}

	if (pRoot->pL_tree != nullptr)
		FindPath(pRoot->pL_tree, expectedSum, path, currentSum, ans);
	if (pRoot->pR_tree != nullptr)
		FindPath(pRoot->pR_tree, expectedSum, path, currentSum, ans);

	currentSum -= pRoot->val;
	path.pop_back();

}

vector<vector<int>> Get_target(BinaryTree* pRoot, int expectedSum)
{

	std::vector<int> path;
	vector<vector<int>> ans;
	int currentSum = 0;
	FindPath(pRoot, expectedSum, path, currentSum, ans);
	
	return ans;
}

int main()
{
	BinaryTree *root = new BinaryTree(1);
	BinaryTree *l1 = new BinaryTree(2);
	BinaryTree *l1l = new BinaryTree(4);
	BinaryTree *l1r = new BinaryTree(5);
	BinaryTree *r1 = new BinaryTree(3);
	BinaryTree *r1l = new BinaryTree(6);
	BinaryTree *r1r = new BinaryTree(7);

	root->pL_tree = l1;
	root->pR_tree = r1;
	l1->pL_tree = l1l;
	l1->pR_tree = l1r;
	r1->pL_tree = r1l;
	r1->pR_tree = r1r;

	int target = 10;
	cin >> target;
	vector<vector<int>> ans;

	ans = Get_target(root, target);
	if (!ans.empty())
		cout << "Find the target" << endl;
	else
		cout << "Can't Find the targe" << endl;
	return 0;
}

想法:

  1. 不要用嘴编程
  2. 找到递归的退出条件
  3. 找不到时找到存储结果的方法
  4. 递归多引用&
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值