剑指offer 二叉树中和为某一值的路径
问题描述
输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
C++代码实现
思路:1、找根结点到叶子结点的值之和等于一个整数
2、声明一个保存路径的二维向量,一个保存当前路径的一维向量
3、使用树的前序遍历,将当前遍历的结点加入当前路径向量组中
4、找到合法路径则加入,否则,遍历左子树和右子树查看是否有合法路径
5、该结点遍历完毕,从当前路径中弹出
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
vector<vector<int> > res;
vector<int> path;
if (!root)
return res;
PreOrder(root, expectNumber, path, res);
return res;
}
void PreOrder(TreeNode* root, int sum, vector<int> &path, vector<vector<int> > &res)
{
path.push_back(root->val);
if (sum == root->val && !root->left && !root->left)
res.push_back(path);
if (root->left)
PreOrder(root->left, sum - root->val, path, res);
if (root->right)
PreOrder(root->right, sum - root->val, path, res);
path.pop_back();
}
};
python2代码实现
注意:列表拼接:object1 + object2不会改变愿列表的值
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
# write code here
res = []
path = []
if not root:
return res
self.sums = expectNumber
self.PreOrder(root, res, [root.val])
return res
def PreOrder(self, root, res, path):
if self.sums == sum(path) and root.left == None and root.right == None:
res.append(path)
if root.left:
self.PreOrder(root.left, res, path + [root.left.val])
if root.right:
self.PreOrder(root.right, res, path + [root.right.val])