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. 二叉树的层序遍历 #18

Open
Geekhyt opened this issue Feb 2, 2021 · 0 comments
Open

102. 二叉树的层序遍历 #18

Geekhyt opened this issue Feb 2, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Feb 2, 2021

原题链接

172e5c5eb722deb3

DFS 深度优先遍历

按照树的深度将每层对应的节点添加到对应层的数组中即可。

const levelOrder = function(root) {
    if (!root) return []
    const res = []
    dfs(root, 0, res)
    return res
};

const dfs = function(root, depth, res) {
    if (!root) return // 递归终止条件
    if (!res[depth]) res[depth] = []
    res[depth].push(root.val) // 存入每层的节点值
    dfs(root.left, depth + 1, res) // drill down
    dfs(root.right, depth + 1, res)
}

BFS 广度优先遍历

根据层次返回其对应的结果集合。

1.边界处理,初始化队列 queue 和存放结果的数组 res。
2.外层循环遍历层级结构,内层循环遍历每一层的子节点。
3.遍历时需要记录当前层的遍历次数 len 以及当前层的节点数组 arr。
4.取得 node 依次出队,并依次存入当前层的节点数组中。
5.若存在左右子节点,则依次入队,并更新 len。
6.遍历完后返回结果 res。

const levelOrder = function(root) {
    if (!root) return []
    const queue = [root]
    const res = []
    while (queue.length > 0) {
      const arr = []
      let len = queue.length
      while (len) {
        let node = queue.shift()
        arr.push(node.val)
        if (node.left) queue.push(node.left)
        if (node.right) queue.push(node.right)
        len--
      }
      res.push(arr)
    }
    return res
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(n)
@Geekhyt Geekhyt added the 中等 label Jun 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant