3ms Java Solution Only Without Queue or Stack


  • 2
    P
    private void getLeaves(List<List<Integer>> ret, List<TreeNode> list) {
    	List<TreeNode> leaves = new ArrayList<TreeNode>();
    	List<Integer> values = new ArrayList<Integer>();
    	Iterator<TreeNode> it = list.iterator();
    	TreeNode node;
    	while(it.hasNext()) {
    		node = it.next();
    		values.add(node.val);
    		if(node.left != null) {
    			leaves.add(node.left);
    		}
    		if(node.right != null) {
    			leaves.add(node.right);
    		}
    	}
    	if(!leaves.isEmpty()) {
    		getLeaves(ret, leaves);
    	}
    	ret.add(values);
    }
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
    	List<List<Integer>> ret = new ArrayList<List<Integer>>();
    	if(root != null) {
    		List<TreeNode> list = new ArrayList<TreeNode>();
    		list.add(root);
    		getLeaves(ret, list);
    		
    	}
    	return ret;
    }

  • 0

    leaves list in getLeaves behaves like a queue only


Log in to reply
 

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