144.二叉树的前序遍历
感觉递归的思路比较清晰,迭代的话得思考一下
递归:
class Solution {
public:
void judge(TreeNode*root,vector<int>&res)
{
if(root==nullptr)
return;
res.push_back(root->val);
judge(root->left,res);
judge(root->right,res);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int>res;
judge(root,res);
return res;
}
};
迭代:
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int>res;
stack<TreeNode*>st;
if(root==nullptr)
return res;
st.push(root);
while(!st.empty())
{
TreeNode*node=st.top();
st.pop();
res.push_back(node->val);
if(node->right) st.push(node->right);
if(node->left) st.push(node->left);
}
return res;
}
};
二刷:
思路一:递归
思路二:迭代(利用栈的特性)
- 栈是先进后出的,左子节点后进入,先计算,所以左子节点的子节点也先计算
94.二叉树的中序遍历
迭代:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int>res;
stack<TreeNode*>st;
TreeNode*cur=root;
while(cur!=nullptr || !st.empty())
{
if(cur!=nullptr){//指针访问节点,访问到最底层
st.push(cur);//将访问的节点放入栈
cur=cur->left;//左
}else
{
cur=st.top();//从栈里弹出的数据,就是要处理的数据
st.pop();
res.push_back(cur->val);//中
cur=cur->right;//右
}
}
return res;
}
};
二刷:
思路一:递归
思路二:迭代,通过栈进行回溯
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int>res;
stack<TreeNode*>st;
TreeNode*cur=root;
while(cur || !st.empty()){
if(cur){
st.push(cur);
cur=cur->left;
}
else{
cur=st.top();//通过栈进行回溯
st.pop();
res.push_back(cur->val);
cur=cur->right;
}
}
return res;
}
};
145.二叉树的后序遍历
迭代:
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
//思路:后序遍历和前序遍历有小小区别
vector<int>res;
stack<TreeNode*>st;
if(root==nullptr)
return res;
st.push(root);
while(!st.empty())
{
TreeNode*node=st.top();
st.pop();
res.push_back(node->val);
if(node->left)
st.push(node->left);
if(node->right)
st.push(node->right);
}
reverse(res.begin(),res.end());
return res;
}
};
二刷:
思路一:递归
思路二:迭代
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int>res;
if(root==nullptr) return res;
stack<TreeNode*>st;
st.push(root);
while(!st.empty()){//进栈:中左右 处理:中右左(最后是右进入,所以中处理完是右)
TreeNode*cur=st.top();
st.pop();
res.push_back(cur->val);
if(cur->left) st.push(cur->left);
if(cur->right) st.push(cur->right);
}
reverse(res.begin(),res.end());//翻转:左右中
return res;
}
};