美文网首页
二叉树中和为某一值的路径

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

作者: Crazy_Bear | 来源:发表于2020-07-29 07:51 被阅读0次
    • 输入一颗二叉树的根节点和一个整数,按字典序打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
    • 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;
        }
    }
    
    • 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>> 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;
        }
    };
    

    相关文章

      网友评论

          本文标题:二叉树中和为某一值的路径

          本文链接:https://www.haomeiwen.com/subject/jldjlktx.html