题解 | #二叉树的之字形层序遍历#
二叉树的之字形层序遍历
http://www.nowcoder.com/practice/47e1687126fa461e8a3aff8632aa5559
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # # @param root TreeNode类 # @return int整型二维数组 # from collections import deque class Solution: def zigzagLevelOrder(self , root ): # write code here if not root: return [] res = [] q = deque([root]) flag = 0 temp = [] while q: size = len(q) temp = [] for i in range(size): curr = q.popleft() if flag == 0: temp.append(curr.val) else: temp.insert(0, curr.val) if curr.left: q.append(curr.left) if curr.right: q.append(curr.right) res.append(temp[:]) flag = 1-flag return res