103. Binary Tree Zigzag Level Order Traversal【M】

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

Subscribe to see which companies asked this question.



這道題的關鍵在於,怎麼判斷每一層,以及,怎麼zigzag地遍歷

一個是,每一層分別記錄,然後根據層數,把結果置反

另一個是,對每一層判斷,分奇數偶數,然後,把結果插入的時候,一個是不斷插在隊伍的最前面,另一個是不斷插在隊伍的最後


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def zigzagLevelOrder(self, root):
        if not root:
            return []

        s = [root]
        s1 = []
        level = 1
        res = []
        while 1:
            temp = []
            for i in s:
                if level % 2 == 1:
                    temp += i.val,
                else:
                    temp = [i.val] + temp

                if i.left:
                    s1 += i.left,
                if i.right:
                    s1 += i.right,
            level += 1
            #print temp
            res += temp,
            if s1 == []:
                break
            s = s1[:]
            s1 = []
        return res






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