解法一:
class Solution
{
public:
void goLongLeftBranch(TreeNode* root,stack<TreeNode*> s) //与前序遍历的沿最左侧通路不同,它只记录而不访问
{
while(root)
{
s.push(root);
if(root->left) root=root->left;
}
}
vector<int> inorderTraversal(TreeNode* root)
{
vector<int> v;
if(root==nullptr) return v;
stack<TreeNode*> s;
while(true)
{
goLongLeftBranch(root,s);
if(s.empty()) return v;
root=s.top();
v.push_back(root->val);
s.pop();
if(root->right) root=root->right;
}
return v;
}
};
解法二:
class Solution
{
public:
vector<int> inorderTraversal(TreeNode* root)
{
vector<int> v;
if(root==nullptr) return v;
stack<TreeNode*> s;
while(true)
{
if(root)
{
s.push(root);
if(root->left) root=root->left;
}
else if(!s.empty())
{
root=s.top();
s.pop();
v.push_back(root->val);
if(root->right) root=root->right;
}
else break;
}
return v;
}
};