Share: Java 2ms Recursive Solution


  • 1
    R
    public class Solution {
        private int maxHeight;
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            maxHeight = getHeight(root);
            
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            for(int row = 0; row < maxHeight; row++) result.add(row, new ArrayList<Integer>());
            
            levelOrder(result, root, 0);
            return result;
        }
        
        public void levelOrder(List<List<Integer>> result, TreeNode root, int height) {
            if(root == null) return;
            result.get(maxHeight - height - 1).add(root.val);
            levelOrder(result, root.left, height+1);
            levelOrder(result, root.right, height+1);
        }
        
        public int getHeight(TreeNode root) {
            return getHeight(root, 0);
        }
        
        public int getHeight(TreeNode root, int height) {
            if(root == null) return 0;
            else {
                int leftHt = getHeight(root.left, height+1);
                int rightHt = getHeight(root.right, height+1);
                return Math.max(leftHt, rightHt)+1;
            }
        }
    }

Log in to reply
 

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