首页 > 其他 > 详细

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

时间:2020-09-18 23:02:59      阅读:55      评论:0      收藏:0      [点我收藏+]

输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。

来源:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof

学习一下遍历二叉树从根节点到叶子节点路径的问题,虽然效率不高,但是毕竟是自己写的,思路清晰,特此记录!

技术分享图片

import java.util.ArrayList;
import java.util.List;

class Solution_34 {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(4);
        root.right = new TreeNode(8);
        root.left.left = new TreeNode(11);
        root.left.left.left = new TreeNode(7);
        root.left.left.right = new TreeNode(2);
        root.right.left = new TreeNode(13);
        root.right.right = new TreeNode(4);
        root.right.right.left = new TreeNode(5);
        root.right.right.right = new TreeNode(1);
        List<List<Integer>> lists = new Solution_34().pathSum(root, 22);
        System.out.println(lists);
    }


    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> lists = new ArrayList<>();
        if (root==null) return lists;
        ArrayList<Integer>  local = new ArrayList<>();
        help(lists,local,root,sum);
        return lists;
    }

    private void help(List<List<Integer>> lists, ArrayList<Integer> local, TreeNode node, int sum) {
        local.add(node.val);
        if (node.left ==null && node.right == null){
            ArrayList<Integer> oldlocal = new ArrayList<>(local);
            int Sum = 0;
            Sum  = local.stream().reduce(Sum, (a, b) -> a + b);
            if (Sum == sum){
                lists.add(oldlocal);
            }
        }
        if (node.left!=null) {
            help(lists, local, node.left, sum);
            local.remove(local.size() - 1);
        }
        if (node.right!=null) {
            help(lists, local, node.right, sum);
            local.remove(local.size() - 1);
        }

    }
}

 

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

原文:https://www.cnblogs.com/iuyy/p/13693477.html

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