zoukankan      html  css  js  c++  java
  • 二叉树中和为某一个值的路径

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

    来源: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 {
    
        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().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);
            }
    
        }
    }
  • 相关阅读:
    蓝桥杯 历届试题 青蛙跳杯子 (BFS)
    HDOJ 1233 (克鲁斯卡尔+并查集)
    HDOJ 1198
    HDOJ 1041 (推公式,大数)水题
    单词接龙
    1284 2 3 5 7的倍数
    2020 排序相减
    isset()和empty()区别
    图像渲染
    Leetcode 328. 奇偶链表
  • 原文地址:https://www.cnblogs.com/iuyy/p/13693477.html
Copyright © 2011-2022 走看看