zoukankan      html  css  js  c++  java
  • 94. 二叉树的中序遍历

    94. 二叉树的中序遍历

    题意

    给定一个二叉树,返回它的中序 遍历数组;

    解题思路

    1. 递归:往左子结点深度递归,在其代码下面加入当前结点的值,接着往右子结点进行深度递归;

    2. 迭代:利用栈后进先出的特性,一直将左子结点都加入到栈中,直到其不存在时,将当前结点的值加入到结果列表中,接着将当前结点的右结点加入到栈中;

    实现

    class Solution(object):
       def inorderTraversal(self, root):
           """
          递归实现
          :type root: TreeNode
          :rtype: List[int]
          """
           result = []
           if not root:
               return result
           
           def helper(node, res):
               if not node:
                   return
               helper(node.left, res)
               res.append(node.val)
               helper(node.right, res)
           
           helper(root, result)
           return result

       def inorderTraversal(self, root):
           """
          迭代实现
          执行用时 : 44 ms, 在Binary Tree Inorder Traversal的Python提交中击败了1.11% 的用户
    内存消耗 : 11.9 MB, 在Binary Tree Inorder Traversal的Python提交中击败了0.89% 的用户
          :type root: TreeNode
          :rtype: List[int]
          """
           result = []
           stack = []
           cur = root
           while cur or stack:
               if cur:
                   stack.append(cur)
                   cur = cur.left
               else:
                   cur = stack.pop()
                   result.append(cur.val)
                   cur = cur.right
           return result

  • 相关阅读:
    java的-D命令行参数 mvn -D参数
    storm1.1运行时问题
    shell 日期转换
    storm单机运行与集群运行问题
    [log4j]Slf4j的包冲突
    搭建Spark源码研读和代码调试的开发环境
    Centos7配置
    mvn本地执行java程序
    HDP和HDF
    Django——如何在Django模板中注入全局变量?——part1
  • 原文地址:https://www.cnblogs.com/George1994/p/10605030.html
Copyright © 2011-2022 走看看