什麼是二叉搜尋樹?
二叉搜尋樹是一顆二叉樹,樹中的每乙個節點的值都是大於其左子樹的值小於其右子樹的值,而且其每一棵子樹都是一顆二叉搜尋樹,其中序遍歷結果是從小到大依次排列的。
以下是二叉搜尋樹的相關操作的**:
#pragma once
#include
#include
#include
typedef
char searchtreetype;
typedef
struct searchtreenode searchtreenode;
void searchtreeinit(searchtreenode** root);
void searchtreeinsert(searchtreenode** root, searchtreetype key);
searchtreenode* searchtreefind(searchtreenode* root, searchtreetype to_find);
void searchtreeremove(searchtreenode** root, searchtreetype key);
#include
"search_tree.h"
void searchtreeinit(searchtreenode** root)
*root =
null;
}searchtreenode* createsearchtreenode(searchtreetype key)
void destorysearchtreenode(searchtreenode* ptr)
void searchtreeinsert(searchtreenode** root, searchtreetype key)
searchtreenode* new_node = createsearchtreenode(key);
if (*root ==
null)
if (key > (*root)->key) else
if (key < (*root)->key) else
return;
}searchtreenode* searchtreefind(searchtreenode* root, searchtreetype to_find)
searchtreenode* cur = root;
if (to_find > cur->key) else
if (to_find < cur->key) else
return cur;
}void searchtreeremove(searchtreenode** root, searchtreetype key)
if (*root ==
null)
//先找到要刪除的節點cur,pre為cur的上乙個節點
searchtreenode* cur =
*root;
searchtreenode* pre = cur;
while (1) else
if (key < cur->key)
} if (cur !=
null)
if(pre->key > cur->key) else
pre->rchild =
null;
destorysearchtreenode(cur);
} else
if (cur->lchild !=
null
&& cur->rchild !=
null)
cur->key = ptr->key;
if (prev == cur) else
destorysearchtreenode(ptr);
}else
if (cur->lchild !=
null
&& cur->rchild ==
null)
searchtreenode* to_delete_lchild = cur->lchild;
cur->key = to_delete_lchild->key;
cur->lchild = to_delete_lchild->lchild;
cur->rchild = to_delete_lchild->rchild;
destorysearchtreenode(to_delete_lchild);
} else
searchtreenode* to_delete_rchild = cur->rchild;
cur->key = to_delete_rchild->key;
cur->lchild = to_delete_rchild->lchild;
cur->rchild = to_delete_rchild->rchild;}}
}///
///以下是測試**//
///#include
#define test_header printf("\n**********==%s**********=\n", __function__)
void preorder(searchtreenode* root)
printf("%c ", root->key);
preorder(root->lchild);
preorder(root->rchild);
}void inorder(searchtreenode* root)
inorder(root->lchild);
printf("%c ", root->key);
inorder(root->rchild);
}void testinit()
void testinsert()
void testfind()
void testremove()
int main()
二叉查詢樹C語言實現
二叉查詢樹c語言實現 1.二叉查詢樹的定義 左子樹不為空的時候,左子樹的結點值小於根節點,右子樹不為空時,右子樹的結點值大於根節點,左右子樹分別為二叉查詢樹 2.二叉查詢樹的最左邊的結點即為最小值,要查詢最小值,只需遍歷左子樹的結點直到為空為止,同理,最右邊的結點結尾最大值,要查詢最大值,只需遍歷右...
二叉查詢樹 C語言實現
二叉查詢樹 若它的左子樹不空,則左子樹上所有結點的值均小於它的根結點的值 若它的右子樹不空,則右子樹上所有結點的值均大於它的根結點的值 它的左 右子樹也分別為二叉查詢樹。在使用遞迴的時候,假如函式有返回值,記得接收返回值,並且保證函式在每個板塊結束後都有return,以防出錯。具體見find ins...
C語言實現二叉樹
1.c語言實現二叉樹中節點間最大距離 includetypedef struct treenode treenode 我們可以將所有的結點的左右子樹的高度和計算一下,然後取出最大值,就是最遠的距離。int getmaxdistance treenode root,int maxdistance in...