Instead of counting levels form root to leaves, this problem is counting levels from leaves to root.

That is the leaves has the height of 1, and the root has the height of Math.max(left-tree-height, right-tree-height) +1.

To here, we can know that we can solve this problem by post-order traversal.

Time complexity: O(n), space complexity: O(n), n is the total nodes on the tree.

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

 

posted on 2022-03-11 04:13  阳光明媚的菲越  阅读(5)  评论(0编辑  收藏  举报