1. 程式人生 > >102. Binary Tree Level Order Traversal - Medium

102. Binary Tree Level Order Traversal - Medium

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

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

    3
   / \
  9  20
    /  \
   15   7

 

return its level order traversal as:

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

 

M1: BFS

建立一個queue用於存放每一層的節點,先把根節點放進queue。在一個迴圈裡,把queue中的值全部pop出來,存成一個數組,再分別找他們的子節點,放入queue中。直到queue為空時結束。

time: O(n), space: O(2^h)  -- 最多一層節點個數

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 
*/ class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); if(root == null) { return res; } Queue<TreeNode> q = new LinkedList<>(); q.offer(root);
while(!q.isEmpty()) { List<Integer> level = new ArrayList<>(); int size = q.size(); for(int i = 0; i < size; i++) { TreeNode tmp = q.poll(); level.add(tmp.val); if(tmp.left != null) { q.offer(tmp.left); } if(tmp.right != null) { q.offer(tmp.right); } } res.add(level); } return res; } }

 

M2: recursion

用一個變數level表示層數,當遞迴到上一層(level=res.size),新建一個新的list存數

time: O(n), space: O(height)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if(root == null) {
            return res;
        }
        levelOrder(root, 0, res);
        return res;
    }
    
    public void levelOrder(TreeNode root, int level, List<List<Integer>> res) {
        if(root == null) {
            return;
        }
        if(res.size() == level) {
            res.add(new ArrayList<>());
        }
        res.get(level).add(root.val);
        
        levelOrder(root.left, level + 1, res);
        levelOrder(root.right, level + 1, res);
    }
}