Binary Tree Zigzag Level Order Traversal - LeetCode

Binary Tree Zigzag Level Order Traversal - LeetCode

题目:

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,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

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

分析:

这道题目的基本思想和   Binary Tree Level Order Traversal (点击打开链接) 一样,只是最后加一个对于i%2 ==1 的列表项的倒序。

代码:

class Solution:
    # @param root, a tree node
    # @return a list of lists of integers
    def zigzagLevelOrder(self, root):
        if not root:
            return []
        res = [[]]
        self.bfs(root,res,0)
        for i in range(len(res)):
            if i%2 == 1:
                res[i]=res[i][::-1]
        return res
    
    def bfs(self,root,l,i):
        if not root:
            return 
        if i == len(l):
            l.append([])
        l[i].append(root.val)
        self.bfs(root.left,l,i+1)
        self.bfs(root.right,l,i+1)



你可能感兴趣的:(LeetCode,python)