LeetCode Binary Tree Zigzag Level Order Traversal

Posted ljbguanli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Binary Tree Zigzag Level Order Traversal相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

[Leetcode] Binary search tree --Binary Search Tree Iterator

Leetcode[110]-Balanced Binary Tree

[Leetcode] Binary tree -- 501. Find Mode in Binary Search Tree

[Lintcode]95. Validate Binary Search Tree/[Leetcode]98. Validate Binary Search Tree

LeetCode 110. Balanced Binary Tree 递归求解

[Leetcode] Balanced Binary Tree