解法一. 使用队列.
根节点入队列,然后根节点出队列,输出根节点,其左右子节点分别入栈。
需要注意的是,此题要一层一层的输出子数组,注意控制一下循环条件就可以了
# 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]]:
result = []
if root is None:
return result
q = [root]
while len(q):
level = []
length = len(q)
for i in range(length):
p = q.pop(0)
level.append(p.val)
if p.left:
q.append(p.left)
if p.right:
q.append(p.right)
result.append(level)
return result
解法二 递归法
# 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]]:
result = []
if root is None:
return result
self.levelhelper(root, 0, result)
return result
def levelhelper(self, p, level, result):
#当level等于数组的长度时,需要新申请一层用于存储
if level == len(result):
result.append([])
if p:
result[level].append(p.val)
else:
return
if p.left:
self.levelhelper(p.left, level+1, result)
if p.right:
self.levelhelper(p.right, level+1, result)
网友评论