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

题目:

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

思路:

使用层序遍历的思路,但是没有用到栈。

程序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
 
class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []
        result = []
        current_level = [root]
        index = 0
        while current_level:
            auxiliary = []
            next_level = []
            for node in current_level:
                auxiliary.append(node.val)
                if node.left:
                    next_level.append(node.left)
                if node.right:
                    next_level.append(node.right)
            if index % 2 == 1:
                result.append(auxiliary[::-1])
            if index % 2 == 0:
                result.append(auxiliary)
            index += 1
            current_level = next_level
        return result

  

posted on   桌子哥  阅读(336)  评论(0编辑  收藏  举报
努力加载评论中...

点击右上角即可分享
微信分享提示