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

  • 相关阅读:
    java学习:字符串比较“==”与“equals”的差异及与c#的区别
    航空8联货运单的作用详解
    flash:二次贝塞尔曲线应用生成飞机路径示意图
    javascript:双链表插入排序
    javascript:算法笔记
    玩聚RT 加入对饭否的统计
    随手小记:创业瞎聊十点
    Python的win32serviceutil之疑似BUG
    撕书记忆法
    中文锐推榜优化·二
  • 原文地址:https://www.cnblogs.com/reboot329/p/5935750.html
Copyright © 2011-2022 走看看