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
  • 相关阅读:
    Single Threaded Execution
    多线程(第三天)
    多线程(第二天)
    IE中float:right单独一行
    web.xml配置
    java调用asmx的webservice
    跨域访问
    jsp页面导入jstl标签
    搜索dwr做即时聊天的时候看到的问题
    LigerUI tree在ie下显示不出来/LigerUI 控件在ie下错乱
  • 原文地址:https://www.cnblogs.com/LLLLgR/p/14978466.html
Copyright © 2011-2022 走看看