面试题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;
}