當前位置:編程學習大全網 - 編程語言 - c++編程實現二叉樹的遍歷,前序,中序,後序,層次,以及在已知兩種遍歷序列的情況下輸出其他兩種序列

c++編程實現二叉樹的遍歷,前序,中序,後序,層次,以及在已知兩種遍歷序列的情況下輸出其他兩種序列

因為樹的定義本身就是遞歸的,所以樹這種數據結構是壹個典型的遞歸型數據結構;

以下為二叉查找樹(中序遍歷)其它的樓主應該是能寫了吧:

typedef int T;

class Bst{

struct Node{

T data;

Node* L;

Node* R;

Node(const T& d):data(d),L(0),R(0){}

};

typedef Node* TreeRoot;

Node* root;

int len;

public:

Bst():root(NULL),len(0){}

~Bst(){Clear(root);}

bool Empty()const{return len==0;}

int Size()const{return len;}

private:

void Ins(TreeRoot& r, Node* p){

if(r==NULL) r=p;

else if(p->data < r->data) Ins(r->L,p);

else Ins(r->R,p);

}

bool Erase(TreeRoot& r, const T& d){

Node*& t = Find(r,d);

if(t==NULL) return false;

if(t->L!=NULL) Ins(t->R, t->L);//左子樹根節點插入右子樹

Node* p = t;

t = t->R;

delete p;

return true;

}

Node*& Find(TreeRoot& r, const T& d){

if(r==NULL) return r;//此時r為空,表示失敗

if(r->data==d) return r;//此時r指向找到的數據,查找成功

if(d < r->data) return Find(r->L,d);

return Find(r->R,d);

}

void Travel(TreeRoot& r){

if(r==NULL) return;

Travel(r->L);

cout << r->data << ' ';

Travel(r->R);

}

void Clear(TreeRoot& r){

if(r==NULL) return;

Clear(r->L);

Clear(r->R);

delete r;

r = NULL;

}

public:

bool Replace(const T& oldd, const T& newd){

if(!Erase(root,oldd)) return false;

Ins(root,new Node(newd));

return true;

}

void Ins(const T& d){Ins(root,new Node(d));++len;}

void Travel(){Travel(root);cout<<endl;}

bool Erase(const T& d){return Erase(root,d);--len;}

bool Find(const T& d){return Find(root,d)!=NULL;}

void Clear(){Clear(root);}

};

int main()

{

Bst b;

b.Ins(20);b.Ins(10);b.Ins(30);b.Ins(15);b.Ins(8);

b.Ins(50);b.Ins(25);

cout << "size=" << b.Size() << endl;

b.Travel();

b.Replace(25,18);b.Replace(10,22);b.Replace(20,35);

cout << "size=" << b.Size() << endl;

b.Travel();

}

  • 上一篇:因為沒錢我在婆家是保姆
  • 下一篇:速求 做c程序 謝謝
  • copyright 2024編程學習大全網