zoukankan      html  css  js  c++  java
  • 每日leetcode-数组-94. 二叉树的中序遍历

    分类:二叉树-二叉树的遍历

    题目描述:

    给定一个二叉树的根节点 root ,返回它的 中序 遍历。

    解题思路:

    递归:

    # 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 inorderTraversal(self, root: TreeNode) -> List[int]:
    
            def inorder(root:TreeNode):
                if not root:
                    return res
                inorder(root.left)
                res.append(root.val)
                inorder(root.right)
            res = []
            inorder(root)
            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 inorderTraversal(self, root: TreeNode) -> List[int]:
            if not root:
                return []
            res,stack = [],[]
            while stack or root: # stack为空且root为null时,说明已经遍历结束
                while root: # 可以深入左子树
                    stack.append(root)
                    root = root.left
                root = stack.pop() # 否则访问栈中节点,并深入右子树
                res.append(root.val)
                root = root.right
            return res
  • 相关阅读:
    五、nginx 配置实例-负载均衡
    四、nginx配置实例-反向代理
    三、nginx配置文件
    二、Nginx 安装
    十二、rpm包的管理
    十一、进程管理
    十、Linux磁盘分区、挂载
    九、定时任务调度
    八、组管理和权限管理
    七、实用指令
  • 原文地址:https://www.cnblogs.com/LLLLgR/p/14978466.html
Copyright © 2011-2022 走看看