题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
# class TreeNode:
# 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
if not pRoot:
return []
res_list = [[pRoot.val]]
node_queue = []
node_queue.append(pRoot.left)
node_queue.append(pRoot.right)
while len(node_queue) > 0:
n_len = len(res_list)
n_res = []
n_node_queue = []
for n_node in node_queue:
if n_node:
if n_len % 2 == 1:
n_res.insert(0, n_node.val)
else:
n_res.append(n_node.val)
n_node_queue.append(n_node.left)
n_node_queue.append(n_node.right)
node_queue = n_node_queue
if len(n_res) > 0:
res_list.append(n_res)
return res_list