LeetCode 102. 二叉树的层序遍历

Posted by cody1991 on August 9, 2020

简单思路:层序遍历

102. 二叉树的层序遍历

DFS 解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function (root) {
  if (!root) return [];
  let result = [];
  dfs(root, 0, result);
  return result;
};

function dfs(root, level, result) {
  if (root) {
    if (!result[level]) result[level] = [];
    result[level].push(root.val);
    dfs(root.left, level + 1, result);
    dfs(root.right, level + 1, result);
  }
}

BFS 算法 (队列)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function (root) {
  if (!root) return [];
  let queue = [root];
  let result = [];

  while (queue.length > 0) {
    const res = [];
    let len = queue.length;

    while (len) {
      const node = queue.shift();
      res.push(node.val);
      if (node.left) queue.push(node.left);
      if (node.right) queue.push(node.right);
      len--;
    }

    result.push(res);
  }

  return result;
};