题目要求:返回树的中序遍历序列
中序遍历的过程:
(1)中序遍历根节点的左子树
(2)访问根节点
(3)中序遍历根节点的右子树
递归版本解法:
递归版本1:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
inorder(root, res);
return res;
}
void inorder(TreeNode* root, vector<int>& res)
{
if(root == nullptr)
return;
inorder(root->left, res); //中序遍历根节点的左子树
res.push_back(root->val); //访问根节点
inorder(root->right, res); //中序遍历根节点的右子树
}
};
递归版本2:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if(root == nullptr)
return res;
vector<int> leftInorder = inorderTraversal(root->left);
res.insert(res.end(), leftInorder.begin(), leftInorder.end());
res.push_back(root->val);
vector<int> rightInorder = inorderTraversal(root->right);
res.insert(res.end(), rightInorder.begin(), rightInorder.end());
return res;
}
};
非递归版本解法:
中序遍历过程:顺着最左侧通路,自底而上依次访问沿途各节点及其右子树。
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if(root == nullptr)
return res;
stack<TreeNode*> s;
TreeNode* cur = root;
while(cur != nullptr || !s.empty())
{
if(cur != nullptr)
{
s.push(cur);
cur = cur->left;
}
else
{
cur = s.top();
s.pop();
res.push_back(cur->val);
cur = cur->right;
}
}
return res;
}
};