102. 二叉树的层序遍历
方法一:广搜,迭代
class Solution(object):
# 相当于广度优先搜索,使用队列实现。
# 队列初始化,将根节点压入队列。
# 当队列不为空,进行如下操作:
# 弹出一个节点,访问,若左子节点或右子节点不为空,将其压入队列。
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
level_queue = []
ans = []
level_queue.append(root)
while level_queue:
num = len(level_queue)
temp = []
while num > 0:
cur = level_queue.pop(0)
temp.append(cur.val)
if cur.left:
level_queue.append(cur.left)
if cur.right:
level_queue.append(cur.right)
num -= 1
ans.append(temp)
return ans
方法二:深搜,递归
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
ans = []
self.dfs(1, root, ans)
return ans
def dfs(self, level, root, ans):
if len(ans) < level:
ans.append([])
ans[level - 1].append(root.val)
if root.left:
self.dfs(level + 1, root.left, ans)
if root.right:
self.dfs(level + 1, root.right, ans)
return ans