Skip to content

二叉树的层序遍历 #7

Open

Description

@YalongYan

题目地址: 二叉树的层序遍历

代码

var levelOrder = function(root) {
  if(!root) {
      return []
  }
  let q = [[root, 0]]
  let arr = []
  while(q.length) {
      let [n, level] = q.shift()
      if(!arr[level]) {
        arr[level] = [n.val] 
      } else {
          arr[level].push(n.val)
      }
      if(n.left) q.push([n.left, level + 1])
      if(n.right) q.push([n.right, level + 1])
  }
  return arr
};

解题思路

层序遍历,记录层数,并把每层数据 推入对应的二维数组中

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions