Skip to content

Latest commit

 

History

History
57 lines (48 loc) · 1.32 KB

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

File metadata and controls

57 lines (48 loc) · 1.32 KB

题目

输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。

从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

样例

给出二叉树如下所示,并给出num=22。
      5
     / \
    4   6
   /   / \
  12  13  6
 /  \    / \
9    1  5   1

输出:[[5,4,12,1],[5,6,6,5]]

参考答案

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    private static List<List<Integer>> ans = new ArrayList<>();
    private static List<Integer> path = new ArrayList<>();

    public List<List<Integer>> findPath(TreeNode root, int sum) {

        dfs(root, sum);
        return ans;
    }

    public void dfs(TreeNode root, int sum){
        if(root == null) return;
        path.add(root.val);
        sum -= root.val;
        if(root.left == null && root.right == null && sum == 0){
            //引用调用,需要复制path内容,不然存在ans中的为引用
            List <Integer> tmp = new ArrayList <>();
            tmp.addAll(path);
            ans.add(tmp);

        }
        dfs(root.left, sum);
        dfs(root.right, sum);
        path.remove(path.size() - 1);

    } 
}