题解 | 二叉树中和为某一值的路径(二)

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

https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca

import java.util.*;

public class Solution {

    ArrayList<ArrayList<Integer>> res_list = new ArrayList<>();
    Stack<Integer> stack = new Stack<>();
    public ArrayList<ArrayList<Integer>> FindPath (TreeNode root, int target) {
        // write code here
        dfs(root,target);

        return res_list;
    }

    public void dfs(TreeNode root, int target){
        if(root == null) return;

        stack.add(root.val);
        if(root.left == null && root.right == null && target - root.val == 0){
            res_list.add(new ArrayList<>(stack));
        }
        dfs(root.left,target - root.val);
        dfs(root.right,target - root.val);
        stack.pop();
    }


}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务