码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Binary Tree Zigzag Level Order Traversal

时间:2017-08-15 18:52:09      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:div   git   ber   pretty   func   ext   列表   key   val   

LeetCode解题之Binary Tree Zigzag Level Order Traversal


原题

实现树的弯曲遍历,即奇数层从左到右遍历。偶数层从右到左遍历。

注意点:

样例:

输入:

    3
   /   9  20
    /     15   7

输出:

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

解题思路

这道题跟 Binary Tree Level Order Traversal 很类似,本质上也是树的广度优先遍历。仅仅是在遍历的时候每一层的遍历顺序不同。

那么我们仅仅要一个变量来区分当前层是从前往后还是从后往前遍历。偷了下懒。当要反过来遍历节点时直接把原有的列表翻转了,而没有在生成列表的时候倒过来加入。

AC源代码

class Solution(object):
    def zigzagLevelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        result = []
        if not root:
            return result
        curr_level = [root]
        need_reverse = False
        while curr_level:
            level_result = []
            next_level = []
            for temp in curr_level:
                level_result.append(temp.val)
                if temp.left:
                    next_level.append(temp.left)
                if temp.right:
                    next_level.append(temp.right)
            if need_reverse:
                level_result.reverse()
                need_reverse = False
            else:
                need_reverse = True
            result.append(level_result)
            curr_level = next_level
        return result


if __name__ == "__main__":
    None

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源代码。

LeetCode Binary Tree Zigzag Level Order Traversal

标签:div   git   ber   pretty   func   ext   列表   key   val   

原文地址:http://www.cnblogs.com/ljbguanli/p/7366760.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!