递归法:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root)
{
vector<int> num;//存放输出结果
inorder(root,num);//中序遍历算法
return num;
}
void inorder(TreeNode* root,vector<int> &num)
{
if(root==NULL)
{
return ;
}
inorder(root->left,num);//左->根->右
num.push_back(root->val);
inorder(root->right,num);
}
};
迭代算法:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root)
{
vector<int> num;
stack<TreeNode*> Stack;
TreeNode* curr=root;
if(root==NULL) return {};
while(curr!=NULL||!Stack.empty())
{
while(curr!=NULL)
{
Stack.push(curr);
curr=curr->left;
}
TreeNode* node=Stack.top();
num.push_back(node->val);
Stack.pop();
curr=node->right;
}
return num;
}
};