1ms - using postorder traversal - check height


  • 0
    T
    public List<List<Integer>> findLeaves(TreeNode root){
                List<List<Integer>> listList = new ArrayList<List<Integer>>();
                helper(root, listList);
                return listList;
            }
    
            private int helper(TreeNode node, List<List<Integer>> lists){
                if (null == node){
                    return 0;
                }
    
                int left = helper(node.left, lists);
                int right = helper(node.right, lists);
    
                int h = Math.max(left, right) + 1;
    
                if (lists.size() == h-1){
                    lists.add(new ArrayList<Integer>());
                }
    
                List<Integer> list = lists.get(h - 1);
    
                list.add(node.val);
    
                return h;
            }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.