二叉树中和为某一值的路径

2020-07-29  本文已影响0人  Crazy_Bear
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;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读