二叉树的遍历分为深度优先遍历和广度优先遍历,深度优先要求先进后出,因此使用栈,广度优先搜索要求先进后出,因此使用队列。
深度优先遍历分为前后中序遍历。
三种顺序都有递归和迭代两种方法。迭代就是用栈模拟递归。
遍历顺序 | |
---|---|
前序 | 中左右 |
中序 | 左中右 |
后序 | 左右中 |
层序 | 从左到右 |
1 层序模板
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x):val(x),left(NULL),right(NULL){
}
};
vector<vector<int>> leverorder(TreeNode* root){
queue<TreeNode*> que;
if(root!=NULL) que.push(root);
vector<vector<int>> res;
while(!que.empty()){
int size=que.size();//记录此时大小 随时在变化
vector<int> tmp;
for(int i=0;i<size;i++){
TreeNode* cur=que.front();
que.pop();
tmp.push_back(cur->val);
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
}
res.push_back(tmp);
}
return res;
}
2 前中后序
2.1递归法
主函数都一样
vector<int> traversalmain(TreeNode* root){
vector<int> res;
traversal(root,res);
return res;
}
前序递归函数
void traversal(TreeNode* cur,vector<int>& result){
if(cur==NULL) return;
result.push_back(cur->val);
traversal(cur->left,result);
traversal(cur->right,result);
}
中序递归函数
void traversal(TreeNode* cur,vector<int>& result){
if(cur==NULL) return;
traversal(cur->left);
result.push_back(cur->val,result);
traversal(cur->right,result);
}
后序递归函数
void traversal(TreeNode* cur,vector<int>& result){
if(cur==NULL) return;
traversal(cur->left,result);
traversal(cur->right,result);
result.push_back(cur->val);
}
2.2 迭代法
由于前序遍历遍历顺序就是处理顺序,因此可以直接用栈实现
vector<int> preorder(TreeNode* root){
stack<TreeNode*> st;
vector<int> res;
if(root!==NULL) st.push(root);
while(!st.empty()){
TreeNode* cur=st.top();
st.pop();
res.push_back(cur->val);
if(cur->left) st.push(cur->right);//先进后出 因此先存放右结点
if(cur->right) st.push(cur->left);
}
return res;
}
后序遍历
由于前序遍历的顺序是 中左右,后序遍历的顺序是 左右中, 因此可以把前序调整为中右左,再反转结果就是左右中
vector<int> preorder(TreeNode* root){
stack<TreeNode*> st;
vector<int> res;
if(root!==NULL) st.push(root);
while(!st.empty()){
TreeNode* cur=st.top();
st.pop();
res.push_back(cur->val);
if(cur->right) st.push(cur->left);//调整顺序
if(cur->left) st.push(cur->right);//先进后出 因此先存放右结点
}
return reverse(res.begin(),res.end());
}
中序遍历
由于中序遍历的处理顺序并不是他的遍历顺序 因此采用栈和指针结合的方法 记录
vector<int> inorderTraversal(TreeNode* root){
stack<TreeNode*> st;
vector<int> res;
//if(root!=NULL) st.push(root);
TreeNode* cur=root;
while(!st.empty()||cur!=NULL){
if(cur!=NULL){
st.push(cur);
cur=cur->left;//左
}
else{
cur=st.top();
st.pop();
res.push_back(cur->val);//中
st.push(cur->right);//右
}
}
return res;
}