二叉树的锯齿形层次遍历

题目描述:给出一棵二叉树,返回其节点值的锯齿形层次遍历(先从左往右,下一层再从右往左,层与层之间交替进行)

样例:

《二叉树的锯齿形层次遍历》

如果之前的二叉树的层次遍历(详见我的博文:点击打开链接)你已经完全搞懂的话,这道题其实基本对你是没有什么意义的,他还是层次遍历,只不过相邻每两层之间输出的顺序相反。

那这个是很容易解决的,设置一个bool型的变量,每次判断是该从左往右,还是从右往在即可。然后每遍历一层,对这个bool型变量取反。

太简单了,直接上代码:

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""


class Solution:
    """
    @param root: The root of binary tree.
    @return: A list of list of integer include 
             the zig zag level order traversal of its nodes' values
    """
    def zigzagLevelOrder(self, root):
        result = []
        if root is None:
            return result
        cur_list = [root]
        level = []
        cur_count, next_count = 1, 0
        left_to_right = False
        while len(cur_list) != 0:
            while cur_count != 0:
                temp = cur_list.pop(0)
                level.append(temp.val)
                cur_count = cur_count - 1
                if temp.left:
                    cur_list.append(temp.left)
                    next_count = next_count + 1
                if temp.right:
                    cur_list.append(temp.right)
                    next_count = next_count + 1
            left_to_right = not left_to_right
            if left_to_right:
                result.append(level)
            else:
                level.reverse()
                result.append(level)
            cur_count = next_count
            next_count = 0
            level = []
        return result
        # write your code here

需要注意的一点是39行,level.reverse()是对列表level做了翻转,它并没有返回值,所以不能写成level = level.
reverse().这是Python的语法规则,注意一下就行

    原文作者:guoziqing506
    原文地址: https://blog.csdn.net/guoziqing506/article/details/51172123
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞