leetCode-Record icon indicating copy to clipboard operation
leetCode-Record copied to clipboard

面试题32 - I. 从上到下打印二叉树

Open fireairforce opened this issue 5 years ago • 0 comments

二叉树的层序遍历

/**
 * 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 stack = [root]
  let res = []
  while (stack.length) {
    let temp = []
    for (let i = 0; i < stack.length; i++) {
      res.push(stack[i].val)
      stack[i].left && temp.push(stack[i].left)
      stack[i].right && temp.push(stack[i].right)
    }
    stack = temp
  }
  return res
}

fireairforce avatar Feb 22 '20 13:02 fireairforce