107. Binary Tree Level Order Traversal II

Given a binary tree, return thebottom-up level ordertraversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree[3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

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

Analysis:

BFS Level order traversal. Use a queue and a counter, when counter reaches zero, we know level finished, renew counter with current size of queue.

Complexity:

Time: O(N)

Space: O(N) - queue will need to store up to max half of the nodes(last row of the tree)

Code:

/**
 * 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) {
        if(root == null)
        {
            return new ArrayList<List<Integer>>();
        }
        List<List<Integer>> returnList = new ArrayList<List<Integer>>();

        Deque<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        int count = 1;
        List<Integer> levelList = new ArrayList<Integer>();
        while(!queue.isEmpty())
        {
            TreeNode cur = queue.poll();
            count--;
            levelList.add(cur.val);
            if(cur.left != null)
            {
                queue.offer(cur.left);
            }
            if(cur.right != null)
            {
                queue.offer(cur.right);
            }
            if(count == 0)
            {
                count = queue.size();
                returnList.add(levelList);
                levelList = new ArrayList<Integer>();
            }
        }

        Collections.reverse(returnList);
        return returnList;
    }
}

results matching ""

    No results matching ""