利用辅助栈的方法进行迭代的前中后遍历。
前序遍历
vector<int> preorder(TreeNode* root){
vector<int> res;
if (root == nullptr){
return res;
}
stack<TreeNode*> s;
TreeNode* curr = root;
while (!s.empty() || curr){
while (curr){
s.push(curr);
res.push_back(curr->val);
curr = curr->left;
}
curr = s.top();
s.pop();
curr = curr->right;
}
return res;
}
中序遍历
vector<int> inorder(TreeNode* root){
vector<int> res;
if (root == nullptr){
return res;
}
stack<TreeNode*> s;
TreeNode* curr = root;
while (!s.empty() || curr){
while (curr){
s.push(curr);
curr = curr->left;
}
curr = s.top();
s.pop();
res.push_back(curr->val);
curr = curr->right;
}
return res;
}
后序遍历:这里是利用先获得根右左的结果,然后将结果反转过来就是左右根,即后序遍历的结果
vector<int> postorder(TreeNode* root){
vector<int> res;
if (root == nullptr){
return res;
}
stack<TreeNode*> s;
TreeNode* curr = root;
while (!s.empty() || curr){
while (curr){
s.push(curr);
res.push_back(curr->val);
curr = curr->right;
}
curr = s.top();
s.pop();
curr = curr->left;
}
reverse(res.begin(), res.end());
return res;
}