Share my java version that beat 86% person


  • 0
    J

    below is my solution:

    public class Solution {
        private List<List<Integer>> list = new ArrayList<List<Integer>>();
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            int length = getTreeLength(root);
            initList(length);
            order(root, length - 1);
            return list;
        }
        
        private void initList(int length){
            for(int i = 0; i < length; i++){
                List<Integer> aList = new ArrayList<Integer>();
                list.add(aList);
            }
        }
        private int getTreeLength(TreeNode root){
            if(root == null) return 0;
            if(root.left == null && root.right == null) return 1;
            return Math.max(getTreeLength(root.left) + 1, getTreeLength(root.right) + 1);
        }
        private void order(TreeNode root, int level){
            if(root == null) return;
            list.get(level).add(root.val);
            if(root.left != null){
                order(root.left, level - 1);
            }
            if(root.right != null){
                order(root.right, level -1);
            }
        }
    }

Log in to reply
 

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