【leetcode】103:二叉树的锯齿形层序遍历

 

 这个题目和leetcode102的题目非常类似,我们只需要对leetcode102的代码稍作修改就可以得到最终的答案了,我们来看看leetcode102的代码:

class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root: return []
        res = []
        queue = [root]
        while queue:
            tmp = []
            for _ in range(len(queue)):
                node = queue.pop(0)
                tmp.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            res.append(tmp)
        return res

我们修改后的代码为:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root: return []
        res = []
        queue = [root]
        i=0
        while queue:
            tmp = []
            for _ in range(len(queue)):
                node = queue.pop(0)
                tmp.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            if i%2==0:
                res.append(tmp)
            else:
                tmp.reverse()
                res.append(tmp)
            i+=1
        return res

也就是在偶数层,对tmp这个list进行逆序输出,对于python的知识点也就是使用reverse方法对list进行逆序就可以了。

posted @ 2021-10-11 21:52  Geeksongs  阅读(27)  评论(0编辑  收藏  举报

Coded by Geeksongs on Linux

All rights reserved, no one is allowed to pirate or use the document for other purposes.