# class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right classSolution(object): defzigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ res = [] if root isNone: return res if root.left isNoneand root.right isNone: res.append([root.val]) return res
height = self.height(root) nodelist = [root] for i inrange(0, height): subnodelist = [] subres = [] while nodelist: cur = nodelist.pop(0) subres.append(cur.val) if cur.left: subnodelist.append(cur.left) if cur.right: subnodelist.append(cur.right)
nodelist = subnodelist if i % 2 != 0: subres.reverse() res.append(subres)
return res
defheight(self, tree): if tree isNone: return0 else: return1 + max(self.height(tree.left), self.height(tree.right))