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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章