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

系列文章:

相关题目:
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
相关推荐
识君啊6 天前
Java 二叉树从入门到精通-遍历与递归详解
java·算法·leetcode·二叉树·深度优先·广度优先
im_AMBER13 天前
Leetcode 124 二叉搜索树的最小绝对差 | 二叉树的锯齿形层序遍历
数据结构·学习·算法·leetcode·二叉树
im_AMBER13 天前
Leetcode 123 二叉树的层平均值 | 二叉树的右视图 | 二叉树的层序遍历
数据结构·学习·算法·leetcode·二叉树
Bear on Toilet14 天前
递归_二叉树_48 . 二叉树最近公共祖先查找
数据结构·算法·二叉树·dfs
im_AMBER15 天前
Leetcode 122 二叉树的最近公共祖先 | 二叉搜索树迭代器
学习·算法·leetcode·二叉树
im_AMBER17 天前
Leetcode 120 求根节点到叶节点数字之和 | 完全二叉树的节点个数
数据结构·学习·算法·leetcode·二叉树·深度优先
im_AMBER18 天前
Leetcode 119 二叉树展开为链表 | 路径总和
数据结构·学习·算法·leetcode·二叉树
2013编程爱好者18 天前
【C++】树的基础
数据结构·二叉树··二叉树的遍历
im_AMBER21 天前
Leetcode 116 相同的树 | 对称二叉树
学习·算法·leetcode·二叉树
Tisfy21 天前
LeetCode 1382.将二叉搜索树变平衡:分治——求得所有节点再重新建树
leetcode·二叉树·深度优先·dfs·题解·二叉搜索树·平衡二叉树