版权声明:本文为博主原创文章,但部分内容来源自互联网,大家可以随意转载,点赞或留言均可! https://blog.csdn.net/csdn_kou/article/details/82829610
二叉树的层序遍历
void printTree(BinaryTree* arr[])
{
queue<BinaryTree*> rel;
rel.push(arr[0]);
while (!rel.empty())
{
BinaryTree* front = rel.front();
printf("%d\n", front->vec);
rel.pop();
if (front->left != nullptr) //判断最前面的左节点是否为空,不是则放入队列
rel.push(front->left);
if (front->right != nullptr)//判断最前面的右节点是否为空,不是则放入队列
rel.push(front->right);
}
}
前序遍历
递归版本
void PreOrder(bintree t){
if(t){
printf("%c ",t->data);
PreOrder(t->lchild);
PreOrder(t->rchild);
}
非递归版本
void preOrder2(BinTree *root) //非递归前序遍历
{
stack<BinTree*> s;
BinTree *p=root;
while(p!=NULL||!s.empty()){
while(p!=NULL){
cout<<p->data<<" ";
s.push(p);
p=p->lchild;
}
if(!s.empty()){
p=s.top();
s.pop();
p=p->rchild;
}
}
}
中序遍历
递归版本
void inOrder1(BinTree *root) //递归中序遍历
{
if(root!=NULL){
inOrder1(root->lchild);
cout<<root->data<<" ";
inOrder1(root->rchild);
}
}
非递归版本
void inOrder2(BinTree *root) //非递归中序遍历
{
stack<BinTree*> s;
BinTree *p=root;
while(p!=NULL||!s.empty()){
while(p!=NULL){
s.push(p);
p=p->lchild;
}
if(!s.empty()){
p=s.top();
cout<<p->data<<" ";
s.pop();
p=p->rchild;
}
}
}
后序遍历
递归版本
void postOrder1(BinTree *root) //递归后序遍历
{
if(root!=NULL)
{
postOrder1(root->lchild);
postOrder1(root->rchild);
cout<<root->data<<" ";
}
}
非递归版本
void postOrder2(BinTree *root) //非递归后序遍历
{
stack<BTNode*> s;
BinTree *p=root;
BTNode *temp;
while(p!=NULL||!s.empty()){
while(p!=NULL) //沿左子树一直往下搜索,直至出现没有左子树的结点 {
BTNode *btn=(BTNode *)malloc(sizeof(BTNode));
btn->btnode=p;
btn->isFirst=true;
s.push(btn);
p=p->lchild;
}
if(!s.empty()){
temp=s.top();
s.pop();
if(temp->isFirst==true) //表示是第一次出现在栈顶
{
temp->isFirst=false;
s.push(temp);
p=temp->btnode->rchild;
}
else //第二次出现在栈顶
{
cout<<temp->btnode->data<<" ";
p=NULL;
}
}
}
}