二叉树的前、中、后序遍历
前言
二叉树是数据结构学习中绕不开的话题。在二叉树的众多题目中,使用dfs(深度优先搜索)和bfs(广度优先搜索)是最常用的,那么学会如何搜索二叉树是必不可少的。
二叉树的搜索分为前,中,后序遍历,又分别对应有递归版本和迭代版本。
前序遍历遵循的原则是:根节点—>左子节点—>右子节点。
中序遍历遵循的原则是:左子节点—>根节点—>右子节点。
后续遍历遵循的原则是:左子节点—>右子节点—>根节点。
代码
#include <bits/stdc++.h>
using namespace std;
//二叉树结构
typedef struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) :val(x),left(NULL),right(NULL) {}
} TreeNode;
class Traversal{
private:
TreeNode *root;
public:
Traversal(TreeNode *root){
this->root = root;
}
// 前序遍历(迭代)
vector<int> preorder(void){
vector<int> result;
if (root == NULL) return result;
stack<TreeNode*> stk;
stk.push(root);
while (!stk.empty()){
TreeNode *cur = stk.top();
stk.pop();
result.push_back(cur->val);
if (cur->right) stk.push(cur->right);
if (cur->left) stk.push(cur->left);
}
return result;
}
// 前序遍历(递归)
vector<int> preorder2(void){
vector<int> result;
function<void(TreeNode*,vector<int>&)> helper = [&](TreeNode* root,vector<int>& result){
if (root == NULL) return ;
result.push_back(root->val);
helper(root->left,result);
helper(root->right,result);
return ;
};
helper(root,result);
return result;
}
// 中序遍历(迭代)
vector<int> inorder(void){
vector<int> result;
stack<TreeNode*> stk;
TreeNode *cur = root;
while (cur != NULL || !stk.empty()){
while (cur != NULL){
stk.push(cur);
cur = cur->left;
}
cur = stk.top();
stk.pop();
result.push_back(cur->val);
cur = cur->right;
}
return result;
}
// 中序遍历(递归)
vector<int> inorder2(void){
vector<int> result;
function<void(TreeNode*,vector<int>&)> helper = [&](TreeNode* root,vector<int>& result){
if (root == NULL) return ;
helper(root->left,result);
result.push_back(root->val);
helper(root->right,result);
return ;
};
helper(root,result);
return result;
}
// 后序遍历(迭代)
vector<int> postorder(void){
vector<int> result;
if (root == NULL) return result;
stack<TreeNode*> stk;
stk.push(root);
while (!stk.empty()){
TreeNode* cur = stk.top();
stk.pop();
result.push_back(cur->val);
if (cur->left) stk.push(cur->left);
if (cur->right) stk.push(cur->right);
}
reverse(result.begin(),result.end());
return result;
}
// 后序遍历(递归)
vector<int> postorder2(void){
vector<int> result;
function<void(TreeNode*,vector<int>&)> helper = [&](TreeNode* root,vector<int>& result){
if (root == NULL) return ;
helper(root->left,result);
helper(root->right,result);
result.push_back(root->val);
return ;
};
helper(root,result);
return result;
}
};
int main(void){
return 0;
}