zoukankan      html  css  js  c++  java
  • 366. Find Leaves of Binary Tree

    一开始想到的是最简单的剪枝法,到底了就手工设置当前NODE为NULL,在JAVA里似乎必须从上级指针来事先,于是要跨级判断操作。

    public class Solution {
        public List<List<Integer>> findLeaves(TreeNode root) 
        {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            List<Integer> tempList;
            while(root != null)
            {
                if(root.left == null && root.right == null)
                {
                    tempList = new ArrayList<>();
                    tempList.add(root.val);
                    res.add(new ArrayList<>(tempList));
                    break;
                }
                tempList = new ArrayList<>();
                helper(res,tempList,root);
                res.add(new ArrayList<>(tempList));
                
                
            }
            
            return res;
            
        }
        
        public void helper(List<List<Integer>> res, List<Integer> tempList, TreeNode root)
        {
            
            
            if(root.left!=null)
            {
                if(root.left.left == null && root.left.right == null)
                {
                    tempList.add(root.left.val);
                    root.left = null;
                }
                else  helper(res,tempList,root.left);
            }
            if(root.right!=null)
            {
                if(root.right.left == null && root.right.right == null)
                {
                    tempList.add(root.right.val);
                    root.right = null;
                }
                else  helper(res,tempList,root.right);
            }
            
        }
        
    }
    

    2MS

    看别人有1MS的办法,记录层数,直接添加到LIST里,写了一个试一试。。

    其实是做了一个POST-ORDER TRAVERSAL。一个NODE的VAL在结果LIST的哪一个里面,取决于他左右两边CHILDREN较深的那个。 返还值是告诉自己PARENT自己这边有几层。。

    public class Solution {
        public List<List<Integer>> findLeaves(TreeNode root) 
        {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            
            int a = helper(res,root);
            
            return res;
            
        }
        
        public int helper(List<List<Integer>> res, TreeNode root)
        {
            if(root == null) return 0;
            
            int depth = Math.max(helper(res,root.left),helper(res,root.right));
            
            if(depth >= res.size())
            {
                res.add(new ArrayList<Integer>());
            }
            res.get(depth).add(root.val);
            
            
            
            return depth+1;
        }
        
    }
    

    1MS。。比上一个好多了

  • 相关阅读:
    js 中的 EventLoop
    线程的并发工具类
    xpath获取某个节点下的全部字节点的文本
    2020中国 .NET开发者大会精彩回顾:葡萄城高性能表格技术解读
    .NET 控件集 ComponentOne V2020.0 Update3 发布,正式支持 .NET 5
    log4net配置
    TP5.1 爬虫
    pip下载慢
    TP5.1 二维码生成
    composer插件集合
  • 原文地址:https://www.cnblogs.com/reboot329/p/5935750.html
Copyright © 2011-2022 走看看