My java 245 ms solution


  • 0
    K

    public class Solution {

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
    
         List<Integer> r = new ArrayList<Integer>();
    	List<List<Integer>> res = new ArrayList<List<Integer>>();
    	Hashtable<TreeNode,Integer> ht= new Hashtable<TreeNode,Integer>();
    	if(root==null){
    		return res;
    	}
    	Queue<TreeNode> queue = new LinkedList<TreeNode>();
    	queue.add(root);
    	ht.put(root, 1);
    	r.add(root.val);
    	res.add(r);
    	int level=1;
    	r = new ArrayList<Integer>();
    	while (!queue.isEmpty()) {
    		TreeNode temp= queue.poll();
    
    		if(level<ht.get(temp)){
    			level=ht.get(temp);
    			res.add(0, r);
    			r = new ArrayList<Integer>();
    		}
    		if(temp.left!=null){
    			queue.add(temp.left);
    			r.add(temp.left.val);
    			ht.put(temp.left, ht.get(temp)+1);
    		}
    		if(temp.right!=null){
    			queue.add(temp.right);
    			r.add(temp.right.val);
    			ht.put(temp.right, ht.get(temp)+1);
    		}
    
    	}
    
    	return res;
    }
    

    }


Log in to reply
 

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