在某一棵二叉树中找出和为某一值的所有路径
输入格式:
第一行 期望值
第二行 按照层序遍历顺序给出的完全二叉树, 若空用 # 表示
输入:
9
6 3 1 # # 4 1 # # # # # # # 1
输出:
6 3
6 1 1 1
#define _CRT_SECURE_NO_WARINGS
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
void Find(TreeNode* root, int expectNumber, vector<vector<int>> &res, vector<int> &path)
{
path.push_back(root->val);
expectNumber -= root->val;
if (!root->left && !root->right)
{
if (expectNumber == 0)
res.push_back(path);
}
if (root->left)
Find(root->left, expectNumber, res, path);
if (root->right)
Find(root->right, expectNumber, res, path);
path.pop_back();
}
vector<vector<int>> FindPath(TreeNode* root, int expectNumber) {
vector<vector<int>> res;
vector<int> path;
if (root)
Find(root, expectNumber, res, path);
return res;
}
TreeNode *ConstructBinaryTree(vector<string> &arr, int len, int i) {
if (len < 1)return NULL;
TreeNode *root = NULL;
if (i < len && arr[i] != "#") {
int val;
stringstream ss;
ss << arr[i];
ss >> val;
root = new TreeNode(val);
if (root == NULL) return NULL;
root->left = ConstructBinaryTree(arr, len, 2 * i + 1);
root->right = ConstructBinaryTree(arr, len, 2 * i + 2);
}
return root;
}
void PreOrderTra(TreeNode *root) //递归前序遍历
{
if (root != NULL)
{
cout << root->val << " ";
PreOrderTra(root->left);
PreOrderTra(root->right);
}
}
int main()
{
int expectNum;
cin >> expectNum;
vector<string> vec;
string input;
while (cin >> input)
{
vec.push_back(input);
if (getchar() == '\n') break;
}
TreeNode* root = ConstructBinaryTree(vec, (int)vec.size(), 0);
//PreOrderTra(root);
vector<vector<int>> res = FindPath(root, expectNum);
for (int i = 0; i < (int)res.size(); i++)
{
for (int j = 0; j < (int)res[i].size(); j++)
cout << res[i][j] << " ";
cout << endl;
}
system("pause");
}