题目:在二元树中找出和为某一值的所有路径
输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如输入整数22 和如下二元树
10
/ \
5 12
/ \
4 7
则打印出两条路径:10, 12 和10, 5, 7。
思路
1、当访问到某一节点时,把该结点的值添加到当前和变量,且把该结点压入栈中。
2、若结点为叶子结点,且当前CurrentSum与期望的expectedSum相等,则打印栈中的结点值,即为所需的路径。
3、若结点不是叶子结点,继续访问它的左孩子结点,访问它的右孩子结点。
4、删除该结点。包括从当前和变量中减去结点值,从栈中弹出结点值。此时,已回到父结点。
程序中的栈,利用STL中的vector,这样简化了编码工作。
具体的findPath函数代码如下:
void findPath(BtreeNode *root, int excepetedSum, vector<int> path, int currentSum) {
currentSum += root->v;
path.push_back(root->v);
if (root->left == NULL && root->right == NULL && currentSum == excepetedSum) {
vector<int>::iterator iter;
for (iter = path.begin(); iter != path.end(); iter++)
cout << *iter << " ";
}else {
if (root->left != NULL)
findPath(root->left, excepetedSum, path, currentSum);
if (root->right != NULL)
findPath(root->right, excepetedSum, path, currentSum);
}
currentSum -= root->v;
path.pop_back();
}
上全部已测试通过的代码:
// printTreePathSum.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
struct BtreeNode {
int v;
struct BtreeNode *left;
struct BtreeNode *right;
};
BtreeNode* insertNode(BtreeNode* root, int value) {
BtreeNode* ptr=root;
BtreeNode* tmpNode;
BtreeNode* newNode = (BtreeNode*)malloc(sizeof(struct BtreeNode));
newNode->v = value;
newNode->left = NULL;
newNode->right = NULL;
if (ptr == NULL)
return newNode;
while (ptr != NULL) {
tmpNode = ptr;
if (ptr->v < value)
ptr = ptr->right;
else
ptr = ptr->left;
}
if (tmpNode->v < value)
tmpNode->right = newNode;
else
tmpNode->left = newNode;
return root;
}
BtreeNode* buildTree() {
BtreeNode* root = NULL;
int a;
while (cin>>a) {
root = insertNode(root, a);
}
return root;
}
void findPath(BtreeNode *root, int excepetedSum, vector<int> path, int currentSum) {
currentSum += root->v;
path.push_back(root->v);
if (root->left == NULL && root->right == NULL && currentSum == excepetedSum) {
vector<int>::iterator iter;
for (iter = path.begin(); iter != path.end(); iter++)
cout << *iter << " ";
}else {
if (root->left != NULL)
findPath(root->left, excepetedSum, path, currentSum);
if (root->right != NULL)
findPath(root->right, excepetedSum, path, currentSum);
}
currentSum -= root->v;
path.pop_back();
}
int _tmain(int argc, _TCHAR* argv[])
{
BtreeNode* root;
root = buildTree();
vector<int> path;
findPath(root, 22, path, 0);
system("pause");
return 0;
}