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

原文地址:https://www.cnblogs.com/reboot329/p/5935750.html