Mert Salık Kişisel Web Sayfası
Bir bilgisayar mühendisi adayının maceraları…
Hoşgeldiniz!
Sample Binary Search Tree Functions

Trees are very important in data structures and algorithms topics, as an introduction of trees here i write some BST (Binary Search Trees) functions for find max depth, numbers of nodes, minimum value etc… I try to use less input variable and make the solutions recursive, if you find better solutions you can share it on your commands or post me for change the current one.
/*
FINDS THE NUMBER OF NODES IN A TREE
*/
int size(struct node* node) {
if (node==NULL) {
return(0);
} else {
return(size(node->left) + 1 + size(node->right));
}
}
/*
FINDS THE MAX DEPTH OF A TREE
*/
int maxDepth(struct node* node) {
if (node==NULL) {
return(0);
}
else {
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);
// use the larger one
if (lDepth > rDepth) return(lDepth+1);
else return(rDepth+1);
}
}
/*
FINDS THE MIN VALUE DATA
*/
int minValue(struct node* node) {
struct node* current = node;
// loop for find the leftmost leaf
while (current->left != NULL) {
current = current->left;
}
return(current->data);
}
/*
CHANGES THE TREE LIKE MIRROR
*/
void mirror(struct node* node) {
if (node==NULL) {
return;
}
else {
struct node* temp;
// do the subtrees
mirror(node->left);
mirror(node->right);
// swap the pointers
temp = node->left;
node->left = node->right;
node->right = temp;
}
}
/*
CHECKS IF THE TREES THE SAME
*/
int sameTree(struct node* a, struct node* b) {
if (a==NULL && b==NULL) return(true);
else if (a!=NULL && b!=NULL) {
return(
a->data == b->data &&
sameTree(a->left, b->left) &&
sameTree(a->right, b->right)
);
}
else return(false);
}
/*
RETURNS TRUE IF THE TREE IS BST AND min>=VALUES<=max */
int isBST(struct node* node) {
return(isBST_(node, INT_MIN, INT_MAX));
}
int isBST_(struct node* node, int min, int max) {
if (node==NULL) return(true);
if (node->datadata>max) return(false);
return
isBST_(node->left, min, node->data) &&
isBST_(node->right, node->data+1, max)
);
}
Bu yazı toplamda 206, bugün ise 2 kez görüntülenmiş
2 Responses to “Sample Binary Search Tree Functions”
Leave a Reply
Sitemi takip ettiğiniz için teşekkür ederim. İyi çalışmalar.

Blogu ingilizceye yazmayan başlaman bence çok iyi olmus. Bana katılmayanlarda olucaktır ancak böylesi daha faydalı.Güzel yorumun için teşekkür ederim Ordinaryus, aslında tüm başlıkları ingilizce yazmayı düşünmüyorum, amacım bilgisayar bilimleri, bölümüm ve işletim sistemleri ile ilgili kısımların tüm dünya tarafından anlaşılabilir birer paylaşım olmasını sağlamak.