力扣 Hot 100 刷题记录 - 二叉树的中序遍历

力扣 Hot 100 刷题记录 - 二叉树的中序遍历

题目描述

二叉树的中序遍历 是力扣 Hot 100 中的一道经典题目,题目要求如下:

给定一个二叉树的根节点 root,返回它的 中序遍历 结果。

示例 1:
输入:root = [1,null,2,3]
输出:[1,3,2]

示例 2:
输入:root = []
输出:[]

示例 3:
输入:root = [1]
输出:[1]


解题思路

中序遍历是二叉树遍历的一种方式,遍历顺序为:左子树 -> 根节点 -> 右子树。常用的实现方法有以下两种:

  1. 递归法

    • 递归地遍历左子树。
    • 访问根节点。
    • 递归地遍历右子树。
  2. 迭代法(借助栈)

    • 使用栈模拟递归过程。
    • 从根节点开始,将所有左子节点入栈。
    • 弹出栈顶节点并访问,然后转向右子节点。

C++ 代码实现

方法一:递归法

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> result;
        inorder(root, result);
        return result;
    }

private:
    void inorder(TreeNode* root, vector<int>& result) {
        if (!root) return; // 递归终止条件

        inorder(root->left, result); // 遍历左子树
        result.push_back(root->val);  // 访问根节点
        inorder(root->right, result); // 遍历右子树
    }
};

方法二:迭代法

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> result;
        stack<TreeNode*> stk;
        TreeNode* curr = root;

        while (curr || !stk.empty()) {
            // 将所有左子节点入栈
            while (curr) {
                stk.push(curr);
                curr = curr->left;
            }

            // 弹出栈顶节点并访问
            curr = stk.top();
            stk.pop();
            result.push_back(curr->val);

            // 转向右子节点
            curr = curr->right;
        }

        return result;
    }
};

你可能感兴趣的:(leetcode,算法,职场和发展)