劍指Offer-24.二叉樹中和爲某一值的路徑(C++/Java)

題目:

輸入一顆二叉樹的跟節點和一個整數,打印出二叉樹中結點值的和爲輸入整數的全部路徑。路徑定義爲從樹的根結點開始往下一直到葉結點所通過的結點造成一條路徑。(注意: 在返回值的list中,數組長度大的數組靠前)html

分析:

LeetCode上有一道相同的題目,之前記錄過:LeetCode 113. Path Sum II路徑總和 II (C++),就再也不講解了。java

程序:

C++數組

class Solution {
public:
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        vector<int> v;
        dfs(root, v, expectNumber);
        return res;
    }
    void dfs(TreeNode* root, vector<int> &v, int sum){
        if(root == nullptr)
            return;
        v.push_back(root->val);
        if(root->left == nullptr && root->right == nullptr){
            if(sum == root->val)
                res.push_back(v);
        }
        else{
            dfs(root->left, v, sum-root->val);
            dfs(root->right, v, sum-root->val);
        }
        v.pop_back();
    }
private:
    vector<vector<int>> res;
};

Javathis

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<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        res = new ArrayList<>();
        ArrayList<Integer> l = new ArrayList<>();
        dfs(root, l, target);
        return res;
    }
    public void dfs(TreeNode root, ArrayList<Integer> l, int sum){
        if(root == null)
            return;
        l.add(root.val);
        if(root.left == null && root.right == null){
            if(root.val == sum){
                res.add(new ArrayList(l));
            }
        }
        else{
            dfs(root.left, l, sum-root.val);
            dfs(root.right, l, sum-root.val);
        }
        l.remove(l.size()-1);
    }
    private ArrayList<ArrayList<Integer>> res;
}
相關文章
相關標籤/搜索