前序遍历:
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> stk;
stk.push(root);
while(!stk.empty()){
root = stk.top();
res.emplace_back(root->val);
stk.pop();
if(root->right) stk.push(root->right);//这里先右后左
if(root->left) stk.push(root->left);
}
return res;
}
};
中序遍历:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> stk;
while(root||!stk.empty()){
while(root){
stk.push(root);
root = root->left;
}
root = stk.top();
stk.pop();
res.emplace_back(root->val);
root = root->right;
}
return res;
}
};
后续遍历:
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> sta;
TreeNode* prev = nullptr;
while(root||!sta.empty()){
while (root){
sta.push(root);
root = root->left;
}
root = sta.top();
sta.pop();
if(!root->right||root->right == prev){
res.emplace_back(root->val);
prev = root;
root = nullptr;
}
else{
sta.push(root);
root = root->right;
}
}
return res;
}
};