题目描述
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
C++
/*
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>>ret;
vector<int>path;
dfs(ret,root,path,expectNumber,0,0);
return ret;
}
void dfs(vector<vector<int>>&ret,TreeNode* root,vector<int>&path,int expectNumber,int len,int sum)
{
if(root == nullptr)
return;
if(len == path.size())
path.push_back(root->val);
else
path[len] = root->val;
if(sum + root->val == expectNumber && root->left == nullptr && root->right == nullptr)
{
vector<int>arr(len+1);
for(int i=0;i<len+1;i++)
{
arr[i] = path[i];
}
ret.push_back(arr);
}
dfs(ret,root->left,path,expectNumber,len+1,sum + root->val);
dfs(ret,root->right,path,expectNumber,len+1,sum + root->val);
}
};
java
import java.util.ArrayList;
import java.util.Stack;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {//思路:用一个栈保存先序遍历所经过的路径,每经过一个节点,target就减去对应节点的值,这样到了叶子节点,如果能够匹配,则target的值会等于叶子节点的值
//root可能为null,可能只有一个节点,可能没有和与target匹配的路径;用一个栈保存所经过的所有节点,当回退的时候再将栈里元素取出
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
ArrayList<ArrayList<Integer>> arrayArrayList = new ArrayList();
if (null == root) {
return arrayArrayList;
}
Stack<Integer> stack = new Stack();
findPathByFST(arrayArrayList, root, target, stack);
return arrayArrayList;
}
private void findPathByFST(ArrayList<ArrayList<Integer>> arrayArrayList, TreeNode root, int target, Stack<Integer> stack) {
stack.push(root.val);
if (root.left == null && root.right == null) {
if (root.val == target) {
ArrayList<Integer> array = new ArrayList();//只有在获取满足条件的路径下才会新建数组
for (Integer data : stack) {
array.add(data);
}
arrayArrayList.add(array);
}
return;
}
if (root.left != null) {
findPathByFST(arrayArrayList, root.left, target-root.val, stack);
stack.pop();
}
if (root.right != null) {
findPathByFST(arrayArrayList, root.right, target-root.val, stack);
stack.pop();
}
}
}
python
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# run:32ms memory:5736k
def FindPath(self, root, expectNumber):
if None == root: return []
return self.FindAPath(root,expectNumber,[],[])
def FindAPath(self,root,expectNumber,path_list,lt):
if None == root: return
expectNumber = expectNumber - root.val
lt.append(root.val)
if expectNumber !=0:
left_lt = list(lt)
self.FindAPath(root.left,expectNumber,path_list,left_lt)
right_lt = list(lt)
self.FindAPath(root.right,expectNumber,path_list,right_lt)
elif root.left == None and root.right == None:
path_list.append(lt)
return path_list