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
  • 相关阅读:
    关于排序算法的记录
    java获取src下文件
    学习HashMap的笔记
    红黑树删除
    学习红黑树过程中的个人总结
    关于二叉树的记录
    关于自动装箱和自动拆箱
    学习函数的时候问题
    Oracle 实现拆分列数据的split()方法
    福大软工 · 最终作业
  • 原文地址:https://www.cnblogs.com/George1994/p/10605061.html
Copyright © 2011-2022 走看看