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

  • 相关阅读:
    取消Git每次拉取、提交推送都要输入密码
    input输入框的oninput和onchange事件
    NPM学习笔记
    命令行语法格式中常用符号的含义
    npm卸载模块报错
    软件的Alpha、Beta、GM、OEM、LTS等版本的含义(转)
    MySQL常用指令
    Git常用指令
    .net Core 解决Form value count limit 1024 exceeded. (文件上传过大)
    EF Core 迁移整理
  • 原文地址:https://www.cnblogs.com/George1994/p/10605030.html
Copyright © 2011-2022 走看看