leetcode -- Binary Tree Zigzag Level Order Traversal -- 重点

https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
结合https://leetcode.com/problems/binary-tree-level-order-traversal/ level order traversal 来看。

参考http://www.cnblogs.com/zuoyuan/p/3722022.html

class Solution(object):

    def preorder(self, root, level, res):
        if root:
            if len(res) < level + 1: res.append([])#注意这个条件
            if level % 2 == 0:
                res[level].append(root.val)
            else:
                res[level].insert(0, root.val)

            self.preorder(root.left, level + 1, res)
            self.preorder(root.right, level + 1, res)


    def zigzagLevelOrder(self, root):
        """ :type root: TreeNode :rtype: List[List[int]] """
        res = []
        self.preorder(root, 0, res)
        return res

你可能感兴趣的:(LeetCode)