剑指Offer——面试题34:二叉树中和为某一值的路径

面试题34:二叉树中和为某一值的路径
题目:输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
在这里插入图片描述

#include<iostream>
#include<vector>
using namespace std;
struct BinaryTreeNode {
	int value;
	BinaryTreeNode* left;
	BinaryTreeNode* right;
};
void FindPath(BinaryTreeNode* pRoot, int expectedSum){
	if(pRoot==NULL) return ;
	vector<int> path;
	int currentSum=0;
	FindPath(pRoot, expectedSum, path, currentSum);
} 
void FindPath(BinaryTreeNode* pRoot, int expectedSum, vector<int>& path, int currentSum) {
	currentSum+=pRoot->value;
	path.push_back(pRoot->value);
	
	// 如果是叶节点, 并且路径上节点值的和等于输入的值, 则打印出这条路径
	bool isLeaf=pRoot->left==NULL&&pRoot->right==NULL;
	if(currentSum==expectedSum && isLeaf){
		printf("A path is found: ");
		vector<int>::iterator it=path.begin();
		for(;it!=path.end();it++){
			printf("%d\t",*it);
		}
		printf("\n");
	}
	
	// 如果不是叶节点, 则遍历它的字节点
	if(pRoot->left!=NULL) FindPath(pRoot->left, expectedSum, path, currentSum); 
	if(pRoot->right!=NULL) FindPath(pRoot->right, expectedSum, path, currentSum);
	
	// 在返回父节点之前, 在路径上删除当前节点
	path.pop_back(); 
}
int main() {

	return 0;
}
发布了42 篇原创文章 · 获赞 43 · 访问量 1057

猜你喜欢

转载自blog.csdn.net/qq_35340189/article/details/104425796