二叉树的前序遍历(利用栈)
1.首先将根节点压入栈
2.栈中的首元素出栈,然后先将其右节点压入栈中,再将栈中的左节点压入栈中(如果左右节点分别存在的话)
3.重复步骤2直到栈为空
class Solution {
public:
stack<TreeNode*> st;
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(root == nullptr) return res;
st.push(root);
while(!st.empty()){
TreeNode* tp = st.top();
st.pop();
res.push_back(tp->val);
if(tp->right) st.push(tp->right);
if(tp->left) st.push(tp->left);
}
return res;
}
};
二叉树的中序遍历(利用栈)
遍历是按照“左根右”的顺序来进行的,按照"右根左"的方法进行遍历,然后翻转一下就可以得到答案
class Solution {
public:
stack<TreeNode*> st;
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
while(root || st.size()){
while(root){
st.push(root);
root = root->right;
}
root = st.top();
res.push_back(root->val);
st.pop();
root = root->left;
}
reverse(res.begin(),res.end());
return res;
}
};
二叉树的后序遍历(利用栈)
遍历是按照“左右根”的顺序来进行的,按照"根右左"的方法进行遍历,然后翻转一下结果就可以得到答案
class Solution {
public:
stack<TreeNode*> st;
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
while(root || st.size()){
while(root){
res.push_back(root->val);
st.push(root);
root = root->right;
}
root = st.top()->left;
st.pop();
}
reverse(res.begin(),res.end());
return res;
}
};