一文搞懂二叉树中序遍历的三种方法

系列文章:

相关题目:
94. 二叉树的中序遍历


中序遍历结果为:4 2 5 1 6 3 7

总体上分为两种框架,递归框架和非递归框架,递归框架又分为两种思路:分解思路和遍历思路。

  • 递归
    1、分解思路 【分解为子问题】
    2、遍历思路 【更新外部变量】
  • 非递归
    3、借助栈

下面代码对三种方法逐一实现。

python 复制代码
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
        
class InorderTraversal:
    """
    94. 二叉树的中序遍历
    https://leetcode.cn/problems/binary-tree-inorder-traversal/
    """

    def solution1(self, root):
        """
        中序遍历
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return []
        return self.solution1(root.left) + [root.val] + self.solution1(root.right)

    def solution1_1(self, root):
        """
        分解思路,同上
        :param root:
        :return:
        """
        res = []
        if not root:
            return []

        res.extend(self.solution1_1(root.left))
        res.append(root.val)
        res.extend(self.solution1_1(root.right))

        return res

    def solution2(self, root):
        """
        遍历思路,一般需要借助递归函数,递归函数没有返回值,靠更新外部变量得到结果
        :param root:
        :return:
        """
        self.res = []
        self.traverse(root)
        return self.res

    def traverse(self, node):
        if not node:
            return

        self.traverse(node.left)
        self.res.append(node.val)
        self.traverse(node.right)

    def solution3(self, root):
        """
        非递归思路,借助栈 实现
        :param root:
        :return:
        """
        res = []
        if not root:
            return res
        else:
            stk = []
            while stk or root:
                if root:
                    stk.append(root)
                    root = root.left
                else:
                    root = stk.pop()
                    res.append(root.val)
                    root = root.right

        return res
相关推荐
闪电麦坤954 天前
数据结构:二叉树的遍历 (Binary Tree Traversals)
数据结构·二叉树·
pusue_the_sun5 天前
数据结构:二叉树oj练习
c语言·数据结构·算法·二叉树
崎岖Qiu6 天前
leetcode100.相同的树(递归练习题)
算法·leetcode·二叉树·力扣·递归
闪电麦坤957 天前
数据结构:在二叉搜索树中插入元素(Insert in a BST)
数据结构·二叉树··二叉搜索树
闪电麦坤958 天前
数据结构:迭代方法(Iteration)实现树的遍历
数据结构·二叉树·
闪电麦坤959 天前
数据结构:N个节点的二叉树有多少种(Number of Binary Trees Using N Nodes)
数据结构·二叉树·
柒柒的代码学习日记21 天前
二叉树链式结构的遍历实现
数据结构·二叉树·链式结构
KarrySmile23 天前
Day17--二叉树--654. 最大二叉树,617. 合并二叉树,700. 二叉搜索树中的搜索,98. 验证二叉搜索树
数据结构·算法·二叉树·二叉搜索树·合并二叉树·最大二叉树·验证二叉搜索树
剪一朵云爱着1 个月前
力扣二叉树的前序中序后序遍历总结
算法·leetcode·二叉树
科大饭桶1 个月前
数据结构自学Days10 -- 二叉树的常用实现
数据结构·算法·leetcode·二叉树·c