三种遍历的基本思想分别是:
先序遍历:根左右
中序遍历:左根右
后序遍历:左右根
code如下
//遍历二叉树
//1.前序遍历
//递归法
void preTraverseTree(TreeNode* root){
if(root==nullptr){
return;
}
cout<<root->val;
preTraverseTree(root->left);
preTraverseTree(root->right);
}
//非递归法
void PreTraverseTree(TreeNode* root){
stack<TreeNode*> S;
S.push(root);
while(!S.empty()){
TreeNode* top = S.top();
cout << top->val;
S.pop();
if(top->right){
S.push(top->right);
}
if(top->left){
S.push(top->left);
}
}
}
//2.中序遍历
//递归法
void midTraverseTree(TreeNode* root){
if(root==nullptr){
return;
}
midTraverseTree(root->left);
cout<<root->val;
midTraverseTree(root->right);
}
//非递归
void MidTraverseTree(TreeNode* root){
stack<TreeNode*> stack;
while(root || !stack.empty()){
while(root!=nullptr){
stack.push(root);
root = root->left;
}
root = stack.top();
stack.pop();
cout << root->val;
root = root->right;
}
}
//3.后序遍历
//递归法
void backTraverseTree(TreeNode* root){
if(!root){
return;
}
backTraverseTree(root->left);
backTraverseTree(root->right);
cout << root->val;
}
//非递归
void BackTraverseTree(TreeNode* root){
//按照"根右左"顺序访问结点,然后反转,反转后就是后序遍历的值
std::vector<int> v;
stack<TreeNode*> stack;
stack.push(root);
while(!stack.empty()){
TreeNode* top = stack.top();
stack.pop();
v.push_back(top->val);
if(top->left){
stack.push(top->left);
}
if(top->right){
stack.push(top->right);
}
}
reverse(v.begin(),v.end());
for(int i:v){
cout<<i;
}
}