二叉查詢樹

2021-06-27 20:12:59 字數 4008 閱讀 2104

二叉查詢樹的的每個節點的左子樹的所有節點的關鍵字的值都小於本節點的關鍵字值,而其所有右子樹的關鍵字值都大於本節點的關鍵字值。

二叉樹的實現:

#ifndef _tree_h

struct treenode;

typedef struct treenode* position;

typedef struct treenode* searchtree;

searchtree makeempty(searchtree t);

position find(elementtype x, searchtree t);

position findmin(searchtree t);

position findmax(searchtree t);

searchtree insert( elementtype x, searchtree t);

searchtree delete (elementtype x, searchtree t);

elementtype retrieve(position p);

#endif   // _tree_h

//place in the implementation file

struct treenode

elementtype element;

searchtree left;

searchtree right;

searchtree 

makeempty(searchtree t)

if(t!=null)

makeempty(t->left);

makeempty(t->right);

free(t);

return null;

position

find(elementtype x, searchtree t)

if (t == null)

return null;

if(xelement)

return find(x, t->left);

else

if(x>t->element)

return find(x, t->right);

else

return t;

position

findmin(searchtree t)

if(t == null)

return null;

else

if(t->left == null)

return t;

else

return findmin(t->left);

position

findmax(searchtree t)

if(t == null)

return null;

else

if(t->right == null)

return t;

else

return findmax(t->right);

searchtree

insert(elementtype x, searchtree  t)

if(t == null)

//create and return a one-node tree

t = malloc(sizeof(struct treenode);

if(t == null)

fatalerror("out of space !");

else 

t->element = x;

t->left = t->right= null;

else

if(xelement)

t->left = insert(x, t->left);

else

if(x>t->element)

t->right = insert(x, t->right);

//else x is in the tree already, we will do nothing.

return t; 

searchtree

delete(elementtype x, searchtree t)

position tmpcell;

if(t == null)

error("element not found");

else

if(x< t->element)   //go left

t->left = delete(x, t->left);

else

if(x > t->element)//go right

t->right = delet(x, t->right);

else //found element to be deleted

if(t->left && t->right)//two children

// replace with smallest in right suntree

tmpcell = findmin(t->right);

t->element = tmpcell->element;

t->right = delete(t->element, t->right);

else// one 0r zero children

tmpcell = t;

if(t->left ==  null)//also handles 0 children

t = t->right;

else if( t->right == null)

t= t->left;

free( tmpcell);//由於要一直迴圈到最後才會刪除元素,因此free要寫在裡邊。

return t;

二叉樹 二叉查詢樹

構建二叉樹,判斷是否為二叉查詢樹,遞迴先序遍歷,非遞迴中序遍歷 include include include include using namespace std 二叉樹結點 struct treenode 鍊錶結點 struct listnode struct tempnodetempnode...

二叉樹 二叉查詢樹

二叉樹 binary tree 一種樹型結構,每個節點最多擁有兩個節點。如下圖 幾種型別的二叉樹 1.full binary tree 每個節點的孩子數 是 0 或者 2.對高度沒有要求。如下圖 2.perfect binary tree 這個就是最完美的樹,顧名思義,所有葉子節點都有相同的深度,並...

樹(樹,二叉樹,二叉查詢樹)

1.定義 n n 0 個結點構成的有限集合。當n 0時,稱為空樹 2.對於任一棵非空樹 n 0 它具備以下性質 1 樹中有乙個稱為 根 root 的特殊結點,用 r 表示 2 其餘結點可分為m m 0 個互不相交的有限集t1,t2,其中每個集合本身又是一棵樹,稱為原來樹的子樹。3.樹的一些性質 1 ...