[LeetCode]题解(python):103 Binary Tree Zigzag Level Order Traversal

题目来源


https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/

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).


题意分析


Input:一个二叉树

Output:一个list

Conditions:每层组成一个list,输出每层的集合,注意是zigzag的,意思是,当为偶数层时,尾部添加;当为奇数层时,首部添加。


题目思路


判断是不是偶数层,决定是否尾部添加


AC代码(Python)

 1 # Definition for a binary tree node.
 2 # class TreeNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution(object):
 9     def preorder(self, root, level, res):
10         if root:
11             if len(res) < level + 1: res.append([])
12             if level % 2 == 0: 
13                 res[level].append(root.val)
14             else:
15                 res[level].insert(0,root.val)
16             self.preorder(root.left, level + 1, res)
17             self.preorder(root.right, level + 1, res)
18     def zigzagLevelOrder(self, root):
19         """
20         :type root: TreeNode
21         :rtype: List[List[int]]
22         """
23         res = []
24         self.preorder(root, 0, res)
25         print res
26         return res

 

posted @ 2016-05-17 16:49  loadofleaf  Views(945)  Comments(0Edit  收藏  举报