#include <iostream>
using namespace std;
const int Maxsize = 100;
struct Node
{
int data;
Node*lchild,*rchild;
};
class Tree
{
public:
Tree(){cout << "輸入節點信息,如果是空請輸入“#”" << endl;
root = Creat(root); }
void PreOrder(){cout <<"前序遍歷得到:";PreOrder(root); cout<<endl;}
int Depth(){cout <<"二叉樹的深度是:"<<Depth(root)<<endl;}
void Count(){Count(root); cout << "二叉樹的結點數是:" << count << endl;} //計算二叉樹節點數
void Exchange(){Exchange(root);cout<<"把左右子樹進行交換"<<endl;} //把二叉樹左右子樹進行交換
void LeverOrder(); //再次層序遍歷
private:
int count = 0;
Node*root;
Node*Creat(Node*root);
void PreOrder(Node *root);
int Depth(Node *root);
void Count(Node *root);
void Exchange(Node*root);
};
//實現構建一顆二叉樹
Node*Tree::Creat(Node*root)
{
char ch;
cin >> ch;
if (ch == '#')root = NULL;
else{
root = new Node;
root->data = ch;
root->lchild = Creat(root->lchild);
root->rchild = Creat(root->rchild);
}
return root;
}
//實現前序遍歷
void Tree::PreOrder(Node *root)
{
if(root==NULL)return;
else{
cout<<root->data;
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
int Tree::Depth(Node *root)//求二叉樹深度
{
int hl=0,hr=0;
if(root==NULL)return 0;
else{
hl=Depth(root->lchild);
hr=Depth(root->rchild);
return max(hl,hr)+1;
}
}
void Tree::Count(Node *root)//實現求二叉樹葉子節點數
{
if(root!=NULL)
{
Count(root->lchild);
count++;
Count(root->rchild);
}
}
void Tree::Exchange(Node*root)//交換左右子樹
{
Node *t;
if(root!=NULL){
Exchange(root->lchild);
Exchange(root->rchild);
t=root->lchild;
root->lchild=root->rchild;
root->rchild=t;
}
}
//層序遍歷
void Tree::LeverOrder()
{cout<<"層序遍歷:";
int rear,front;
Node *Q[50];
Node *q;
front=rear=-1;
if(root==NULL)return;
Q[++rear]=root;
while(front!=rear)
{
q=Q[++front];
cout<<q->data;
if(q->lchild!=NULL)Q[++rear]=q->lchild;
if(q->rchild!=NULL)Q[++rear]=q->rchild;
}
}
int main()
{
Tree B;
B.PreOrder();
B.Depth();
B.Count();
B.Exchange();
B.LeverOrder();
return 0;
}
已解決= =, 一開始的DATA應該定義為CHAR類型的= =