102. 二叉树的层序遍历

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

 

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

    3
   /   9  20
    /     15   7

返回其层序遍历结果:

[
  [3],
  [9,20],
  [15,7]
]
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function(root) {
  let res = []
  if(!root){
    return res
  }  
  let stack = []
  stack.push([root])
  while(stack.length){
    let curLevel = stack.shift()
    let len = curLevel.length    
    let level = []
    let tmp = []
    for(let i = 0; i < len; i++){
      let node = curLevel[i]
      if(node){
        tmp.push(node.val)
      }
      if(node.left)
      {
        level.push(node.left)
      }
      if(node.right){
        level.push(node.right)
      }      
    }
    if(level.length){
      stack.push(level)
    }  
    res.push(tmp)  
  }
  return res
};

Python3

from typing import List


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:

      res = list()
      if not root:
        return res

      stack = list()
      stack.append([root])
      while stack:
        curLevel = stack.pop(0)
        level = list()
        resLevel = list()
        for node in curLevel:
          if node:
            resLevel.append(node.val)
            if node.left:
              level.append(node.left)
            if node.right:
              level.append(node.right)
        if level:
            stack.append(level)
        if resLevel:
            res.append(resLevel)
      return res

102. 二叉树的层序遍历

上一篇:io+properties


下一篇:gin中ctx.Next()的作用