ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

【力扣每日一题】力扣94二叉树的中序遍历

2026/9/19 15:37:57 拓冰建站 浏览量
【力扣每日一题】力扣94二叉树的中序遍历

题目来源

力扣94二叉树的中序遍历

题目概述

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

思路分析

就是简单的树的中序遍历,使用递归和迭代的方式都可以实现。

代码实现

java实现

java使用迭代方式实现

public class Solution {public List<Integer> inorderTraversal(TreeNode root) {List<Integer> res = new ArrayList<>();Stack<TreeNode> stack = new Stack<>();while (root != null || !stack.isEmpty()) {// 左孩子入栈,等待方法while (root != null) {stack.push(root);root = root.left;}// 出栈被访问root = stack.pop();res.add(root.val);// 如果有右孩子,再访问右孩子root = root.right;}return res;}
}

c++实现

c++使用递归方式实现

class Solution {
public:vector<int> res = vector<int>();vector<int> inorderTraversal(TreeNode* root) {if (root == nullptr) {return res;}inorderTraversal(root->left);res.push_back(root->val);inorderTraversal(root->right);return res;}
}