Java solution without queue, using DFS


  • 0
    B
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int height(TreeNode root)
        {
            if(root == null)return 0;
            
            
            return 1+Math.max(height(root.left),height(root.right));
        }
        
        public void solve(TreeNode root, List<List<Integer>> l,int h, int len)
        {
            
            if(root == null)return;
            //push to corresponding array
            
            l.get(len-h).add(root.val);
            solve(root.left,l,h+1,len);
            solve(root.right,l,h+1,len);
        }
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            
            
            int h  = height(root);
            
            
            List<List<Integer>> l = new ArrayList<List<Integer>>();
            
            for(int i=0;i<h;i++)
            {
                l.add(new ArrayList<Integer>());   
            }
            
            solve(root,l,0,h-1);
            return l;
            
        }
    }
    

Log in to reply
 

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