先序
先序是根左右的,因为我们用栈,栈是先进后出的,我们要先将右子树加进去,这样右子树就会在下面,就是后被遍历的。
因为根左右,所以往下一层马上是根操作,所以最多只能往下一层,我们用if来控制往下走!而不是while一直走
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(root == nullptr) res;
stack<TreeNode*> sta;
sta.push(root);
while(!sta.empty()){
root = sta.top();
sta.pop();
res.push_back(root->val);
//因为根左右往下一层就马上又要到根了,所以往下走一层就行了
//因为我们要先把左子树加入res,stack后进先出,所以把左子结点后面入栈
if(root->right != nullptr){
sta.push(root->right);
}
if(root->left != nullptr){
sta.push(root->left);
}
}
return res;
}
};
中序
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if(root == nullptr) return res;
stack<TreeNode*> sta;
//因为root不是一开始就入栈的,所以有两个判断条件,为什么不是一开始就入栈呢
//因为这样子最后加入root->right之后,不确定root->right是否为空,如果对其取left操作,可能出错
//所以我们在把左子结点加入sta的时候要把root本身加进去,不是判断root->left后加进去
while(root !=nullptr || !sta.empty()){
while(root != nullptr){
sta.push(root);
root = root->left;
}
root = sta.top();
sta.pop();
res.push_back(root->val);
root = root->right;
}
return res;
}
};
后序
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if(root == nullptr) return res;
//后序就是魔改前序,前序是根左右,后序是左右根
//只要把根左右变成根右左然后入栈,最后再依次出栈就是后序遍历的结果
stack<TreeNode*> sta;
stack<TreeNode*> sta1;
sta.push(root);
while(!sta.empty()){
root = sta.top();
sta.pop();
sta1.push(root);
//因为要先遍历右子树,所以先把左子树入栈
if(root->left != nullptr){
sta.push(root->left);
}
if(root->right != nullptr){
sta.push(root->right);
}
}
while(!sta1.empty()){
res.push_back(sta1.top()->val);
sta1.pop();
}
return res;
}
};
后序的另一种方法,不需要另一个辅助栈
我们要的是左右根,先序是根左右,我们把先序改成根右左,然后把结果数组reverse一下就行了
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
//魔改前序,前序是根左右,后序是左右根,因为前序我们的操作是根右入栈左入栈
//所以后序我们的操作是根左右,让其加入一个辅助栈,辅助栈弹出后顺序是左右根,为什么先把左的入栈,因为左的先入,右的就在上面了,然后再次入辅助栈的时候,左的在上面,右就在下面了
vector<int> res;
if(root == nullptr) return res;
stack<TreeNode*> sta;
//stack<int> sta1;
sta.push(root);
while(!sta.empty()){
root = sta.top();
sta.pop();
res.push_back(root->val);
if(root->left !=nullptr){
sta.push(root->left);
}
if(root->right !=nullptr){
sta.push(root->right);
}
}
// while(!sta1.empty()){
// res.push_back(sta1.top());
// sta1.pop();
// }
reverse(res.begin(),res.end());
return res;
}
};