二叉树的递归遍历
文章链接:代码随想录 (programmercarl.com)
视频链接:每次写递归都要靠直觉? 这次带你学透二叉树的递归遍历!| LeetCode:144.前序遍历,145.后序遍历,94.中序遍历_哔哩哔哩_bilibili
笔记
- 递归遍历最简单,每次改变访问根结点的位置即可得到前中后遍历
C++代码
class Solution {
public:
void traversal(TreeNode* cur,vector<int>&vec){
if(cur==nullptr)return;
vec.push_back(cur->val);
traversal(cur->left,vec);
traversal(cur->right,vec);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int>res;
traversal(root,res);
return res;
}
};
class Solution {
public:
void traversal(TreeNode*cur,vector<int>&res){
if(cur==nullptr)return;
traversal(cur->left,res);
traversal(cur->right,res);
res.push_back(cur->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
traversal(root,res);
return res;
}
};
class Solution {
public:
void traversal(TreeNode* cur,vector<int>& res){
if(cur==nullptr)return;
traversal(cur->left,res);
res.push_back(cur->val);
traversal(cur->right,res);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
traversal(root,res);
return res;
}
};
迭代遍历
笔记
- 前序遍历入栈先中再右后左
- 中序遍历左走到底再向右走
- 后序遍历根据前序遍历改编
C++代码
前序遍历
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int>res;
stack<TreeNode*> st;
if(root==nullptr)return res;
st.push(root);//root
while(!st.empty()){
TreeNode* cur=st.top();
st.pop();
res.push_back(cur->val);//visit root
if(cur->right)st.push(cur->right);//right
if(cur->left)st.push(cur->left);//left
}
return res;
}
};
中序遍历
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
TreeNode* cur=root;
while(!st.empty() || cur!=nullptr){
if(cur!=nullptr){
st.push(cur);
cur=cur->left;//l
}else{
cur=st.top();
st.pop();
res.push_back(cur->val);//n
cur=cur->right;//right
}
}
return res;
}
};
后序遍历
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* cur=st.top();
st.pop();
res.push_back(cur->val);
if(cur->left!=nullptr)st.push(cur->left);
if(cur->right!=nullptr)st.push(cur->right);
}
reverse(res.begin(),res.end());
return res;
}
};
统一迭代遍历
笔记
- 改变左中右那三句的位置
C++代码
中序为模板
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
if (root != NULL) st.push(root);
while (!st.empty()) {
TreeNode* node = st.top();
if (node != NULL) {
st.pop(); // 将该节点弹出,避免重复操作,下面再将右中左节点添加到栈中
if (node->right) st.push(node->right); // 添加右节点(空节点不入栈)
st.push(node); // 添加中节点
st.push(NULL); // 中节点访问过,但是还没有处理,加入空节点做为标记。
if (node->left) st.push(node->left); // 添加左节点(空节点不入栈)
} else { // 只有遇到空节点的时候,才将下一个节点放进结果集
st.pop(); // 将空节点弹出
node = st.top(); // 重新取出栈中元素
st.pop();
result.push_back(node->val); // 加入到结果集
}
}
return result;
}
};