考察二叉树的层序遍历
问题描述 leetcode代码:
# 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: Optional[TreeNode]) -> List[List[int]]:
result = []
def recur(node,depth):
if node:
if depth==len(result):
result.append([])
result[depth].append(node.val)
recur(node.left,depth+1)
recur(node.right,depth+1)
recur(root,0)
return result
运行结果: