题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
http://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
#
# @param root TreeNode类
# @return int整型二维数组
#
class Solution:
def levelOrder(self , root ):
return []
return res
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
#
# @param root TreeNode类
# @return int整型二维数组
#
class Solution:
def levelOrder(self , root ):
# write code here
#若根节点为空时,返回空列表
if root is None:return []
res = []
#pt为节点队列
pt = [root]
#节点队列为空时,结束,输出结果res
while pt:
# 用来存放每一层的结果
a = []
#一层一层节点遍历
for i in range(len(pt)):
#pop出最左边(即pt[0])节点
p = pt.pop(0)
#将当前节点的值存放到a中
a.append(p.val)
#若当前节点存在左子节点,将左子节点加入pt队列
if p.left is not None:
pt.append(p.left)
#若当前节点存在右子节点,将右子节点加入pt队列
if p.right is not None:
pt.append(p.right)
#当前层遍历结束,将当前层的结果放到res中
res.append(a)return res