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
  • 相关阅读:
    [BZOJ1303][CQOI2009]中位数图
    [BZOJ1192][HNOI2006]鬼谷子的钱袋
    9.5题解
    9.3题解
    9.2题解
    9.1题解
    8.29题解
    8.28题解
    8.23<2>题解
    8.23<1>题解
  • 原文地址:https://www.cnblogs.com/LLLLgR/p/14978466.html
Copyright © 2011-2022 走看看