zoukankan      html  css  js  c++  java
  • 103. 二叉树的锯齿形层次遍历

    103. 二叉树的锯齿形层次遍历

    题意

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

    解题思路

    和题目102一致;

    实现

    class Solution(object):
       def zigzagLevelOrder(self, root):
           """
          :type root: TreeNode
          :rtype: List[List[int]]
          """
           result = []
           if not root:
               return result

           def helper(node, depth, res, is_reverse):
               """
              利用前序遍历的思想
              """
               if not node:
                   return
               # 超出递归的长度表明是新的一层,则新添加数组
               if depth >= len(res):
                   res.append([])
               # 可以理解成每个node都能对应到树的depth
               if is_reverse:
                   res[depth].insert(0, node.val)
               else:
                   res[depth].append(node.val)
               if node.left:
                   helper(node.left, depth+1, res, not is_reverse)
               if node.right:
                   helper(node.right, depth+1, res, not is_reverse)

           helper(root, 0, result, False)
           return result
  • 相关阅读:
    RunLoop详解
    NSURLConnection基本用法(苹果原生)
    NSThread 基本使用
    NSOperation/NSOperationQueue详细使用介绍
    JSON解析
    XML解析
    GCD详细用法
    [Java]手动编译Java
    [Selenium] Grid 介绍
    [SoapUI] 循环遍历某个Test Case下的所有Test Step,将Cookie传递给这些Test Step
  • 原文地址:https://www.cnblogs.com/George1994/p/10605061.html
Copyright © 2011-2022 走看看