/*
* 给定一个整数sum,找出二叉树路径上的结点值的总和等于sum的所有路径
* 方法:先序遍历 + 递归 + 栈
*/
#include<iostream>
#include<vector>
using namespace std;
struct BinaryTreeNode {
int value;
BinaryTreeNode* left;
BinaryTreeNode* right;
BinaryTreeNode(int value):left(NULL),right(NULL){
this->value = value;
}
};
BinaryTreeNode* createBinaryTree(int value) {
if(value <= 0)
return NULL;
BinaryTreeNode* pNode = new BinaryTreeNode(value);
pNode->left = createBinaryTree(--value);
pNode->right = createBinaryTree(value);
return pNode;
}
void findPathRecursive(BinaryTreeNode* pNode, vector<int>& path,
int currentSum, int sum) {
currentSum += pNode->value;
path.push_back(pNode->value);
bool isLeaf = pNode->left == NULL && pNode->right == NULL;
if(currentSum == sum && isLeaf) {
vector<int>::iterator iter = path.begin();
for(;iter != path.end(); iter++)
cout << *iter << "->";
cout << "end" << endl;
}
// 递归遍历和计算左、右子树的路径
if(pNode->left != NULL)
findPathRecursive(pNode->left, path, currentSum, sum);
if(pNode->right != NULL)
findPathRecursive(pNode->right, path, currentSum, sum);
// 返回父节点前删除当前结点
path.pop_back();
}
void findPath(BinaryTreeNode* pNode, int sum) {
if(pNode == NULL)
return;
vector<int> path;
int currentSum = 0;
findPathRecursive(pNode, path, currentSum, sum);
}
void inOrder(BinaryTreeNode* root) {
if(root == NULL)
return;
if(root->left)
inOrder(root->left);
cout << root->value << " ";
if(root->right)
inOrder(root->right);
}
int main() {
BinaryTreeNode* root = createBinaryTree(4);
cout << "中序遍历" << endl;
inOrder(root);
cout <<endl<<endl;
cout << "sum = 10" <<endl;
findPath(root, 10);
cout << "sum = 7" <<endl;
findPath(root, 7);
cout << "sum = 6" <<endl;
// findPath(root, 6);
}
剑指offer(面试题34):二叉树中和为某一值的路径
最新推荐文章于 2024-06-25 21:14:18 发布