Similar easy Python as level order probelm, using height.


  • 0
    W
    class Solution(object):
        def zigzagLevelOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            if root==None:
                return []
            q,re,re_line=[],[],[]
            height,keep_height=1,1
            q.append((root,1))
            while q:
                node,height=q.pop(0)
                print node.val,height, keep_height
                if height==keep_height+1:
                    if keep_height%2==0:
                        re_line=re_line[::-1]
                    re.append(re_line)
                    re_line=[]
                    re_line.append(node.val)
                elif height==keep_height:
                    re_line.append(node.val)
                keep_height=height
                if node.left:
                    q.append((node.left,height+1))
                if node.right:
                    q.append((node.right,height+1))
            if keep_height%2==0:
                re_line=re_line[::-1]
            re.append(re_line)
            return re

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.