71. Binary Tree Zigzag Level Order Traversal

题目

https://www.lintcode.com/problem/construct-binary-tree-from-inorder-and-postorder-traversal/description?_from=ladder&&fromId=2

实现

  1. 使用 stack 来遍历每一层即可
  2. 要注意的要设置一个 flag 来判断下一层的遍历顺序

代码

class Solution:
    """
    @param root: A Tree
    @return: A list of lists of integer include the zigzag level order traversal of its nodes' values.
    """

    def zigzagLevelOrder(self, root):
        if root is None:
            return []

        stack = [root]
        results = []
        next_from_left = False

        while len(stack) != 0:
            results.append([node.val for node in stack])
            next_stack = []

            for i in range(len(stack)):
                node = stack.pop()

                if next_from_left:
                    if node.left:
                        next_stack.append(node.left)
                    if node.right:
                        next_stack.append(node.right)
                else:
                    if node.right:
                        next_stack.append(node.right)
                    if node.left:
                        next_stack.append(node.left)

            stack = next_stack
            next_from_left = not next_from_left

        return results

你可能感兴趣的:(71. Binary Tree Zigzag Level Order Traversal)