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);
            }
    
        }
    }
  • 相关阅读:
    设置IIS允许下载.config文件
    SQL Server 触发器
    MVC参数自动装配
    sql之left join、right join、inner join的区别
    C# 之泛型详解
    Frameset使用教程
    网页引用Font Awesome图标
    ubuntu下apache2 安装 配置 卸载 CGI设置 SSL设置
    深入理解JAVA I/O系列二:字节流详解
    深入理解JAVA I/O系列三:字符流详解
  • 原文地址:https://www.cnblogs.com/iuyy/p/13693477.html
Copyright © 2011-2022 走看看