/**
 * public class TreeNode {
 *   public int key;
 *   public TreeNode left;
 *   public TreeNode right;
 *   public TreeNode(int key) {
 *     this.key = key;
 *   }
 * }
 */
public class Solution {
  public List<List<Integer>> layerByLayer(TreeNode root) {
    // Write your solution here.
    List<List<Integer>> result = new ArrayList<>();
    if (root == null) {
      return result;
    }
    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    while(!queue.isEmpty()) {
      int size = queue.size();
      List<Integer> temp = new ArrayList<>();
      for (int i = 0; i < size; i++) {
        TreeNode cur = queue.poll();
        temp.add(cur.key);
        if (cur.left != null) {
          queue.offer(cur.left);
        }
        if (cur.right != null) {
          queue.offer(cur.right);
        }
      }
      result.add(temp);
    }
    return result;
  }
}

assumption: root 非空。

approach: expand a node s, generate its neighbors' nodes.(leftsub node, and right subnode); maintain a queue and put all generated node into queue; do a loop until the queue is empty.

time : O(n) since we visited all the nodes in the tree once.

use arraylist to store the result, and a temp arraylist to store each level integer.

results matching ""

    No results matching ""