- 输入一颗二叉树的根节点和一个整数,按字典序打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
- Java 代码
import java.util.ArrayList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<Integer> tmp = new ArrayList<>();
public ArrayList<ArrayList<Integer>> res = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(null == root) {
return res;
}
tmp.add(root.val);
if(null == root.left && null == root.right && (target-root.val)==0){
res.add(new ArrayList<Integer>(tmp));
}
FindPath(root.left, target-root.val);
FindPath(root.right, target-root.val);
tmp.remove(tmp.size()-1);
return res;
}
}
/*
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>> ans;
vector<int> tmp;
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
if(!root) return ans;
tmp.push_back(root->val);
if(!root->left && !root->right && expectNumber - root->val ==0)
ans.push_back(tmp);
FindPath(root->left,expectNumber - root->val);
FindPath(root->right,expectNumber - root->val);
tmp.pop_back();
return ans;
}
};
网友评论