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

方法一:递归
函数代码一:
class Solution {
vector<int>res;
public:
vector<int> inorderTraversal(TreeNode* root) {
if(!root)
{
return vector<int>{};
}
inorderTraversal(root->left);
res.push_back(root->val);
inorderTraversal(root->right);
return res;
}
};
函数代码二:
class Solution {
vector<int>res;
public:
vector<int> inorderTraversal(TreeNode* root) {
dfs(root,res);
return res;
}
void dfs(TreeNode* root,vector<int>&res)
{
if(!root)
{
return;
}
dfs(root->left,res);
res.push_back(root->val);
dfs(root->right,res);
}
};
函数代码三:
class Solution {
vector<int>res;
public:
vector<int> inorderTraversal(TreeNode* root) {
if(!root)
{
return res;
}
dfs(root,res);
return res;
}
void dfs(TreeNode* root,vector<int>&res)
{
if(!root)
{
return;
}
if(root->left)
{
dfs(root->left,res);
}
res.push_back(root->val);
if(root->right)
{
dfs(root->right,res);
}
}
};

本文介绍了一种使用递归方法实现二叉树中序遍历的算法,通过三个不同的函数代码示例展示了如何有效地进行节点遍历,并将遍历结果存储在向量中返回。
1576

被折叠的 条评论
为什么被折叠?



