Leetcode刷题(30)二叉树专题:树的中序遍历(递归和迭代)

题目

94.二叉树的中序遍历

Leetcode刷题(30)二叉树专题:树的中序遍历(递归和迭代)_第1张图片

难度:中等
题目分析:二叉树的题目基于递归的解法,跟套模板一样,都不需要怎么思考。重点在于掌握迭代的方法,这样有助于理解遍历的过程。

中旬遍历,是 左 - 中 - 右的顺序

2.解法一:递归

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        # 使用递归来中序遍历
        res = []
        def dfs(root):
            if not root:
                return
            
            dfs(root.left)
            res.append(root.val)
            dfs(root.right)
            
        dfs(root)
        return res

2.1 运行结果:

Leetcode刷题(30)二叉树专题:树的中序遍历(递归和迭代)_第2张图片
Leetcode刷题(30)二叉树专题:树的中序遍历(递归和迭代)_第3张图片

2. 解法二:非递归的方法

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
    # 使用迭代的方法
        # 构建一个while 循环,一直到最左的节点

        res, stack = [],[]

        while stack or root:
            while root:
                stack.append(root)
                root = root.left
            
            node = stack.pop()
            res.append(node.val)
            root = node.right

        return res

2.1 运行结果:

Leetcode刷题(30)二叉树专题:树的中序遍历(递归和迭代)_第4张图片Leetcode刷题(30)二叉树专题:树的中序遍历(递归和迭代)_第5张图片

2.2 分析:

中序遍历和后序遍历都需要构建两个循环。

第二个循环的目的是让我们的指针可以到达最左下方的叶节点,然后就可以输出该节点的数值。

之后,遍历方向进入右子树。

你可能感兴趣的:(刷题,学习札记)