1. 程式人生 > >資料結構實驗---二叉樹的遍歷

資料結構實驗---二叉樹的遍歷

 

#include<stdio.h>
#include <iostream>
#include<string.h>
#include<stack>//採用世界先進,國際一流的棧容器,方便省事不除錯 
#include<algorithm>
using namespace std;
typedef struct binode
{
	char data;
	binode *lch,*rch;
}*bitree;
typedef struct node1
{
    binode *btnode;
    bool isFirst;
}BTNode;
void CreateBiTree(bitree &T)
{
	char ch;
	ch=getchar();
	if(ch =='#')
	{
		T=NULL;
	}
	else
	{
		T = (bitree)malloc(sizeof(binode));
		T->data = ch;
		CreateBiTree(T->lch);
		CreateBiTree(T->rch);
	}
}
void xianxu(binode *root)     //非遞迴前序遍歷 
{
    stack<binode*> s;
    binode *p=root;
    while(p!=NULL||!s.empty())
    {
        while(p!=NULL)
        {
            printf("%c ",p->data);
            s.push(p);
            p=p->lch;
        }
        if(!s.empty())
        {
            p=s.top();
			s.pop();
			p=p->rch;
        }
    }
}
void zhongxu(binode *T)      //非遞迴中序遍歷
{
   bitree curr = T;   
    stack<bitree> s;  
    while(curr != NULL || !s.empty())  
    {  
        while(curr != NULL)  
        {  
            s.push(curr);  
            curr = curr->lch;  
        } 
        if(!s.empty())  
        {  
            curr = s.top();  
            s.pop();  
            cout<<curr->data<<" ";  
            curr = curr->rch;  
        }  
    }  
}
void houxu(binode *root)    //非遞迴後序遍歷
{
    stack<BTNode*> s;
    binode *p=root;
    BTNode *temp;
    while(p!=NULL||!s.empty())
    {
        while(p!=NULL)              //沿左子樹一直往下搜尋,直至出現沒有左子樹的結點 
        {
            BTNode *btn=new BTNode;
            btn->btnode=p;
            btn->isFirst=true;
            s.push(btn);
            p=p->lch;
        }
        if(!s.empty())
        {
            temp=s.top();
            s.pop();
            if(temp->isFirst==true)     //表示是第一次出現在棧頂 
             {
                temp->isFirst=false;
                s.push(temp);
                p=temp->btnode->rch;    
            }
            else                        //第二次出現在棧頂 
             {
                printf("%c ",temp->btnode->data);
                p=NULL;
            }
        }
    }    
}
int depth(binode *root)
{
	int hl,hr;
	if(!root)
	return 0;
	else
	{
		hl=depth(root->lch);
		hr=depth(root->rch);
		return max(hl,hr)+1;
	}
}
int main()
{
	while(1)
	{
		binode *T;
		printf("建造二叉樹:");
		CreateBiTree(T);
		binode *x1,*x2,*x3;
		x1=x2=x3=T;
		printf("\n");
		printf("樹的先序遍歷:");//建樹的最後遞迴結束時T自然就是根節點 
		xianxu(x1); 
		printf("\n");
		printf("\n");
		printf("樹的中序遍歷:");
		zhongxu(x2); 
		printf("\n");
		printf("\n");
		printf("樹的後序遍歷:");
		houxu(x3); 
		printf("\n");
		printf("\n");
		printf("樹的深度為:%d\n",depth(T));
		printf("\n");
	}	
	return 0;
}