首页 > 其他 > 详细

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

时间:2020-05-03 20:39:14      阅读:52      评论:0      收藏:0      [点我收藏+]

技术分享图片

思路:

技术分享图片

题解:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    LinkedList<List<Integer>> res = new LinkedList<>();
    LinkedList<Integer> path = new LinkedList<>(); 
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        recur(root, sum);
        return res;
    }
    void recur(TreeNode root, int tar) {
        if(root == null) return;
        path.add(root.val);
        tar -= root.val;
        if(tar == 0 && root.left == null && root.right == null)
            res.add(new LinkedList(path));//深拷贝
        recur(root.left, tar);
        recur(root.right, tar);
        path.removeLast();
    }
}

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

原文:https://www.cnblogs.com/treasury/p/12823250.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!