题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pRoot TreeNode类
# @return int整型二维数组
#
class Solution:
def Print(self , pRoot: TreeNode) -> List[List[int]]:
# write code here
left2right = True
list2root = [pRoot]
if not pRoot:
return None
result = []
result.append([list2root[0].val])
while list2root: # 因为这里是从第二层开始遍历的,所以别忘了在上面把跟节点的值加上
temp = []
temp2 = []
for ele in list2root:
if ele.left:
temp.append(ele.left)
temp2.append(ele.left.val)
if ele.right:
temp.append(ele.right)
temp2.append(ele.right.val)
list2root = temp
if list2root: # 如本层有节点才添加到result列表里,否则就多添加了一层空列表
left2right = not left2right
if left2right:
result.append(temp2)
else:
result.append(temp2[::-1])
return result