zoukankan      html  css  js  c++  java
  • 【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进行逆序就可以了。

  • 相关阅读:
    [leetcode]Palindrome Partitioning II
    [wikioi]传纸条
    [leetcode]Palindrome Partitioning
    [leetcode]Convert Sorted List to Binary Search Tree
    [topcoder]ActivateGame
    [topcoder]NinePuzzle
    [topcoder]BestRoads
    [topcoder]IncreasingSubsequences
    [leetcode]Surrounded Regions
    CF 432B :Football Kit
  • 原文地址:https://www.cnblogs.com/geeksongs/p/15395178.html
Copyright © 2011-2022 走看看