前序遍历
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int>res;
stack<TreeNode*> s;
if(!root) return res;
s.push(root);
while(!s.empty())
{
TreeNode * marker=s.top();
s.pop();
res.push_back(marker->val);
if(!marker->left&&!marker->right)
continue;
if(marker->right)
s.push(marker->right);
if(marker->left)
s.push(marker->left);
}
return res;
}
};
后序遍历
```css
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int>res;
stack<TreeNode*> s;
if(!root) return res;
s.push(root);
while(!s.empty())
{
TreeNode * marker=s.top();
s.pop();
res.push_back(marker->val);
if(!marker->left&&!marker->right)
continue;
if(marker->left)
s.push(marker->left);
if(marker->right)
s.push(marker->right);
}
reverse(res.begin(),res.end());
return res;
}
};
中序遍历
```cpp
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root)
{
vector<int>res;
if(!root) return res;
stack<TreeNode*>s;
while(root||!s.empty())
{
while(root)
{
s.push(root);
root=root->left;
}
TreeNode*marker=s.top();
s.pop();
res.push_back(marker->val);
root=marker->right;
}
return res;
}
};