//总结二叉树中的先序,中序,后序,层序:
//一.递归:
#include<bits/stdc++.h>
#include
#include
#include
using namespace std;
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x):
val(x),left(NULL),right(NULL) {}
};
//先序递归:
void preOrderRecur(TreeNode *head)
{
if(head==NULL) return ;
cout<val<<",";
preOrderRecur(head->left);
preOrderRecur(head->right);
}
//中序递归:
void inOrderRecur(TreeNode *head)
{
if(head==NULL) return ;
inOrderRecur(head->left);
cout<val<<",";
inOrderRecur(head->right);
}
//后序递归:
void posOrderRecur(TreeNode *head)
{
if(head==NULL) return ;
posOrderRecur(head->left);
posOrderRecur(head->right);
cout<val<<",";
}
//二.非递归形式:
//先序非递归:
void preOrderunRecur(TreeNode head)
{
if(head==NULL) return;
stack<TreeNode> nstack;
nstack.push(head);
while(!nstack.empty())
{
TreeNode *head=nstack.top(); //取出栈顶元素;
cout<val<<",";
nstack.pop(); //弹出栈顶元素;
if(head->right!=NULL) //先进后出
{
nstack.push(head->right);
}
if(head->left!=NULL)
{
nstack.push(head->left);
}
}
}
//中序非递归:
void inOrderunRecur(TreeNode head)
{
if(head==NULL) return ;
stack<TreeNode> nstack;
while(!nstack.empty()||head!=NULL)
{
if(head!=NULL)
{
nstack.push(head);
head=head->left;
}
else{
head=nstack.top();
cout<val<<",";
nstack.pop();
head=head->right;
}
}
}
//后序非递归:
void posOrderunRecur(TreeNode head)
{
if(head==NULL) return ;
stack<TreeNode> nstack1,nstack2;
nstack1.push(head);
while(!nstack1.empty())
{
TreeNode *head=nstack1.top();
nstack2.push(head);
nstack1.pop();
if(head->left!=NULL)
{
nstack1.push(head->left);
}
if(head->right!=NULL)
{
nstack1.push(head->right);
}
}
while(!nstack2.empty())
{
cout<<nstack2.top()->val<<",";
nstack2.pop();
}
}
//二叉树的层序遍历:BFS
void LevelOrder(TreeNode head)
{
if(head==NULL) return ;
queue<TreeNode> nqueue;
nqueue.push(head);
while(!nqueue.empty())
{
TreeNode *head=nqueue.front();
cout<val<<",";
nqueue.pop();
if(head->left!=NULL)
{
nqueue.push(head->left);
}
if(head->right!=NULL)
{
nqueue.push(head->right);
}
}
}
int main()
{
TreeNode* head = new TreeNode(5);
head->left = new TreeNode(3);
head->right = new TreeNode(8);
head->left->left = new TreeNode(2);
head->left->right = new TreeNode(4);
head->right->left = new TreeNode(7);
head->right->right = new TreeNode(10);
head->right->left->left = new TreeNode(6);
head->right->right->left = new TreeNode(9);
head->right->right->right = new TreeNode(11);
printf(“递归**”);
cout << "\npre-order: ";
preOrderRecur(head);
cout << "\nin-order: ";
inOrderRecur(head);
cout << "\npos-order: ";
posOrderRecur(head);
cout << “\n*******非递归********”;
cout << "\npre-order: ";
preOrderunRecur(head);
cout << "\nin-order: ";
inOrderunRecur(head);
cout << "\npos-order: ";
posOrderunRecur(head);
cout<<"\nLevel-order:";
LevelOrder(head);
return 0;
}