题目描述

【leetcode】102. 二叉树的层次遍历

解题思路

就是一个简单的循环,不用递归

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

class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        res_all=[]
        if root is None:
            return []
        nodeList=[root]
        while True:
            if nodeList==[]:
                break 
            tmp=[]
            res=[]
            for node in nodeList:
                res.append(node.val)
                if node.left is not None:
                    tmp.append(node.left)
                if node.right is not None:
                    tmp.append(node.right)
            res_all.append(res)
            del res
            nodeList=tmp
            del tmp
  

        return res_all
        
                
        

相关文章:

  • 2022-01-12
  • 2021-11-23
  • 2022-02-12
  • 2022-01-24
  • 2021-06-25
猜你喜欢
  • 2021-09-21
  • 2021-07-27
  • 2021-09-04
  • 2021-07-11
  • 2022-12-23
  • 2021-07-31
  • 2021-04-22
相关资源
相似解决方案