Leetcode–Binary Tree Level Order Traversal II

The Problem:

Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]

Notes:

  1. Same as Binary Tree Level Order Traversal, just need to use a stack to reverse the order.

Java Solution

/**
 * Definition for binary tree
 * 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 LinkedList<List<Integer>>();
        Stack<List<Integer>> st = new Stack<List<Integer>>();
        if(root==null) return result;
        Queue<TreeNode> curLv = new LinkedList<TreeNode>();
        curLv.add(root);
        Queue<TreeNode> nxtLv = new LinkedList<TreeNode>();
        List<Integer> one = new ArrayList<Integer>();
        while(!curLv.isEmpty() || !nxtLv.isEmpty()){
            while(!curLv.isEmpty()){
                TreeNode top = curLv.poll();
                one.add(top.val);
                if(top.left!= null){
                    nxtLv.add(top.left);
                }
                if(top.right!= null){
                    nxtLv.add(top.right);
                }
            }
            st.push(one);
            one=new ArrayList<Integer>();
            curLv = nxtLv;
            nxtLv = new LinkedList<TreeNode>();
        }
        while(!st.empty())
            result.add(st.pop());
        return result;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s