Professional Documents
Culture Documents
A binary tree T, is called binary search tree (or binary sorted tree), if each node N of T has the following
property. The value at N is greater than every value in the left subtree of N and is less than or equal to
every value in the right subtree of N. A BST holds the following properties:
Inorder Tree Walk: A binary search tree is an AVL tree if and only if
each node in the tree satis es the following property: Rotations: A tree rotation is required when we have
inserted or deleted a node which leaves the tree in an unbalanced form.
During this type of walk, we visit the root of a subtree between the left subtree visit and right subtree
visit.
Inorder (x):
If x ≠ NIL {
Inorder (left[x]);
print key[x];
Inorder (right[x]);
If x ≠ NIL {
print key[x];
Preorder (left[x]);
NEXT
Preorder (right[x]);
If x ≠NIL {
Postorder (left[x]);
Postorder (right[x]);
It takes θ (n) time to walk (inorder, preorder and pastorder) a tree of n nodes.
On a binary search tree of height h, Search, Minimum, Maximum, Successor, Predecessor, Insert,
and Delete can be made to run in O(h) time.
The height of the Binary Search Tree equals the number of links from the root node to the deepest
node.
The disadvantage of a BST is that if every item which is inserted to be next is greater than the previous
item, then we will get a right skewed BST or if every item which is to be inserted is less than to the
previous item, then we will get a left skewed BST.
NEXT
So, to overcome the skewness problem in BST, the concept of AVL- tree or height balanced tree came into
existence.
Balanced Binary Trees: Balancing ensures that the internal path lengths are close to the optimal n log n.
A balanced tree will have the lowest possible overall height. AVL trees and B trees are balanced binary
trees.
Example 1: Number of leaves in a binary search tree
int total = 0;
return 1;
if(node->Left!= 0)
total += numberofleaves(node->Left);
if(node->Right!=0)
total += numberofleaves(node->Right);
return total;
if(root == NULL)
*height = 0;
return 0;
return(root);
{
NEXT
if(root==NULL) return true;
return true;
Example 6: Write a recursive function to count the number of nodes in binary tree
NEXT