Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

Have you met this question in a real interview? Yes
Example
Given binary tree {3,9,20,#,#,15,7},

3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

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

Solution: BFS

public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
    if(root == null) {
        return new ArrayList<>();
    }  
    ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> list = new ArrayList<Integer>();
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.add(root);
    int cur = 1, next = 0;
    while(!queue.isEmpty()) {
        TreeNode tmp = queue.poll();
        list.add(tmp.val);
        cur--;
        if(tmp.left != null) {
            queue.add(tmp.left);
            next++;
        }
        if(tmp.right != null) {
            queue.add(tmp.right);
            next++;
        }
        if(cur == 0) {
            cur = next;
            next = 0;
            res.add(list);
            list = new ArrayList<Integer>();
        }
    }
    return res;
}

Binary Tree Level Order Traversal II

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).

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]
]

Solution: BFS, reverse result at the end

public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
    if(root == null) {
        return new ArrayList<>();
    }  
    ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> list = new ArrayList<Integer>();
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.add(root);
    int cur = 1, next = 0;
    while(!queue.isEmpty()) {
        TreeNode tmp = queue.poll();
        list.add(tmp.val);
        cur--;
        if(tmp.left != null) {
            queue.add(tmp.left);
            next++;
        }
        if(tmp.right != null) {
            queue.add(tmp.right);
            next++;
        }
        if(cur == 0) {
            cur = next;
            next = 0;
            res.add(list);
            list = new ArrayList<Integer>();
        }
    }
    Collections.reverse(res);
    return res;
}

results matching ""

    No results matching ""