二叉搜尋樹的C 實現

2021-09-25 06:10:22 字數 2150 閱讀 7890

參考:

標頭檔案

#ifndef debug_lrn_treenode_h

#define debug_lrn_treenode_h

void echo(int i);

class treenode;

void inorder_tree_walk(treenode* x);

void preorder_tree_walk(treenode* x);

treenode* tree_minmum(treenode* x);

treenode* tree_maxmum(treenode* x);

treenode* tree_search(treenode* x, int k);

treenode* tree_successor(treenode* x);

treenode* tree_predecessor(treenode* x);

void tree_insert(treenode* t, treenode* z);

void transplant(treenode* t, treenode* u,treenode* v);

void tree_delete(treenode* t, treenode* z);

class treenode;

#endif //debug_lrn_treenode_h

原始檔

#include #include #include "treenode.h"

using namespace std;

void echo(int i)

treenode::treenode()

treenode::treenode(int val)

treenode::~treenode() = default;

void inorder_tree_walk(treenode* x) else

return;

}void preorder_tree_walk(treenode*x)

}treenode* tree_minmum(treenode* x)

treenode* tree_maxmum(treenode* x)

treenode* tree_search(treenode* x, int k)

treenode* tree_successor(treenode* x)//大於x.key的最小關鍵字的節點為後繼

return y;

}treenode* tree_predecessor(treenode* x)//小於x.key的最大關鍵字的節點為前驅

return y;

}void tree_insert(treenode* t, treenode* z) //t是現在的bst的樹根

; treenode* y = nullptr;

treenode* x=t;

while(x != nullptr)

z->p = y;

if(z->key < y->key)

y->left = z;

else y->right = z;

}//刪除節點

void transplant(treenode* t, treenode* u,treenode* v)//用一顆子樹代v替另乙個子樹u

else if(u == u->p->left)

else;

if(v != nullptr)

}void tree_delete(treenode* t, treenode* z)

transplant(t, z, y);

y->left = z->left;

y->left->p = y;

}}

測試:

#include #include #include #include #include #include #include "treenode.h"

using namespace std;

using namespace cv;

void test_bst();

for(auto i:a)

inorder_tree_walk(t);cout

c 實現二叉搜尋樹

h部分 ifndef binaryserchtree bst h define binaryserchtree bst h include template class bst 宣告 template class element template class bstnode template cla...

c 實現二叉搜尋樹

c 實現二叉搜尋樹 include include using namespace std struct node class tree tree tree void tree creattree node rt,int n if rt data n else else void tree leve...

二叉搜尋樹的c 實現

includeusing namespace std templateclass bstree template class bstnode bstnode t d,bstnode l null,bstnode r null data d leftchild l rightchild r bstno...