Simple Java from solution of Binary Tree Level Order Traversal I


  • 0
    K
       Just reverse the result...I know it's lame
    
    
     /**
         * Definition for a binary tree node.
         * public class TreeNode {
         *     int val;
         *     TreeNode left;
         *     TreeNode right;
         *     TreeNode(int x) { val = x; }
         * }
         */
        public class Solution {
            public List<List<Integer>> levelOrderBottom(TreeNode root) {
                List<List<Integer>> result = new ArrayList<List<Integer>>();
                addlevel(root, 0, result);
                for(int i = 0, j = result.size() - 1; i < j; i++) {
                result.add(i, result.remove(j));}
                return result;
                
            }
            public static List<List<Integer>> addlevel(TreeNode root, int level, List<List<Integer>> result){
                if (root == null) return result;
                if (result.size() == level){
                    result.add(new ArrayList<Integer>());
                }
                result.get(level).add(root.val);
                addlevel(root.left, level+1, result);
                addlevel(root.right, level+1, result);
                return result;
            }
            
        }

Log in to reply
 

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