Binary Tree Level Order Traversal II @ LeetCode (Python)
Linked List Cycle II @ LeetCode (Python)

Binary Tree Zigzag Level Order Traversal @ LeetCode (Python)

kitt posted @ 2014年3月05日 00:19 in LeetCode , 2243 阅读

同Binary Tree Level Order Traversal一样, 需要记录层的信息。dict[0] = [3], dict[1] = [9, 20]。

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @return a list of lists of integers
    def preOrder(self, root, level):
        if level not in Solution.L:
            Solution.L[level] = [root.val]
        else:
            Solution.L[level].append(root.val)
        if root.left:
            self.preOrder(root.left, level + 1)
        if root.right:
            self.preOrder(root.right, level + 1)
    
    def zigzagLevelOrder(self, root):
        res = []
        if root == None: return res
        Solution.L = {}
        self.preOrder(root, 0)
        for i in sorted(Solution.L.keys()):
            if i % 2 == 0:
                res.append(Solution.L[i])
            else:
                res.append(Solution.L[i][::-1])
        return res

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter