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。。比上一个好多了

  • 相关阅读:
    AdvComboBox
    带有可选选项的输入文本框(组合框)
    使用JavaScript为整个网站创建通用的Twitter按钮
    高速绘图控件
    Outlook样式分组列表控件
    CComboBox的禁用项目
    一个自定义的WPF滑块按钮
    23个设计模式
    MVC执行流程
    SQL注入面试
  • 原文地址:https://www.cnblogs.com/reboot329/p/5935750.html
Copyright © 2011-2022 走看看