Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

二叉树的层序遍历-102 #30

Open
sl1673495 opened this issue May 15, 2020 · 0 comments
Open

二叉树的层序遍历-102 #30

sl1673495 opened this issue May 15, 2020 · 0 comments
Labels
BFS 广度优先遍历 DFS 深度优先遍历 二叉树

Comments

@sl1673495
Copy link
Owner

给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。

示例:

二叉树:[3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

经典模板题,DFS 和 BFS 都可以。

DFS

遍历的时候记录一下 level,每次递归都把 level+1,即可获得正确的层级,push 到对应的数组中即可:

let levelOrder = function (root) {
  let res = [];
  let dfs = (node, level = 0) => {
    if (!node) return;

    if (!res[level]) {
      res[level] = [];
    }

    res[level].push(node.val);

    dfs(node.left, level + 1);
    dfs(node.right, level + 1);
  };

  dfs(root);
  return res;
};

BFS

利用队列,while 中对于每轮的节点开一个 for 循环加入到数组的一层中即可。

/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
let levelOrder = function (root) {
  if (!root) return [];
  let ret = [];
  let queue = [root];

  while (queue.length) {
    let len = queue.length;
    let level = [];
    ret.push(level);
    for (let i = 0; i < len; i++) {
      let node = queue.shift();
      level.push(node.val);

      if (node.left) {
        queue.push(node.left);
      }
      if (node.right) {
        queue.push(node.right);
      }
    }
  }

  return ret;
};
@sl1673495 sl1673495 added BFS 广度优先遍历 DFS 深度优先遍历 二叉树 labels May 15, 2020
@sl1673495 sl1673495 changed the title 二叉树的层序遍历 二叉树的层序遍历-102 Jul 7, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
BFS 广度优先遍历 DFS 深度优先遍历 二叉树
Projects
None yet
Development

No branches or pull requests

1 participant