【LeetCode】94. 二叉树的中序遍历

xiaoxiao2025-08-12  39

题目链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal/description/

题目描述

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

示例

输入: [1,null,2,3] 1 2 / 3

输出: [1,3,2]

解决方法

采用递归,深度优先遍历

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { vector<int> res; public: vector<int> inorderTraversal(TreeNode* root) { //采用递归,深度优先遍历 if (root){ inorderTraversal(root->left); res.push_back(root->val); inorderTraversal(root->right); } return res; } };
转载请注明原文地址: https://www.6miu.com/read-5034750.html

最新回复(0)