【Leetcode_总结】103. 二叉树的锯齿形层次遍历 - python

Q:

给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

例如:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回锯齿形层次遍历如下:

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

链接:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/description/

思路:正常的二叉树层次遍历+对输出进行处理

代码:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def zigzagLevelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        res = []
        que = [root]
        if root == None:
            return res
        while que:
            tempList = []
            for i in range(len(que)):
                node = que.pop(0)
                tempList.append(node.val)
                if node.left:
                    que.append(node.left)
                if node.right:
                    que.append(node.right)
            res.append(tempList)
        temp = []
        for i in range(len(res)):
            if i%2 == 0:
                temp.append(res[i])
            else:
                temp.append(res[i][::-1])
        return (temp)
            

猜你喜欢

转载自blog.csdn.net/maka_uir/article/details/86523153