Binary search tree

Generally the tree have one root node and child node, each child node can have leaf nodes.



How elements will insert in a tree ?
 Assume your going to insert a element 10 in the tree.
 As there are no elements it will insert as root node.
Then again if we try to insert element 20, it will insert right side of tree because 20  is greater then 10.
What if element is less then 10 ? - It goes to left side of tree.
Finally the tree will look like this.



Note: Here I know there is a problem with Unbalanced tree
Unbalanced tree execution time is very high to overcome this there are plenty of algorithm we will see those in my future posts.



Then how will be the tree traversal?
There are three way to walk through the tree, they are.
  1. Inorder
  2. Preorder
  3. Postorder
Assume there is tree like this.

Inorder:
  First it goes to left node then root then right node.
   A --> B --> C

Preorder:
  First it goes to root node then left node then right node.
  B --> A --> C
Postorder:
  First it goes to left node then right node then finally root node.
  A --> C --> B


Note:
Inorder tree always gives us sorting order.
 
We can construct the Binary tree only with postorder and preorder.


Sample code for Binary  tree:

public class MleBinaryTree {
 MleBinaryTree left, right;
 int data;

 public MleBinaryTree(int value) {
  this.data = value;
 }

 public MleBinaryTree insert(MleBinaryTree root, int element) {
  if (root == null) {
   root = new MleBinaryTree(element);
   return root;
  }
  if (element > root.data) {
   root.right = insert(root.right, element);
  } else {
   root.left = insert(root.left, element);
  }
  return root;
 }

 public void insert(int value) {
  insert(this, value);
 }

 // Inorder left---> root --> right
 public void inorder(MleBinaryTree root) {
  if (root != null) {
   inorder(root.left);
   System.out.println(root.data);
   inorder(root.right);
  }
 }

 public void inorder() {
  inorder(this);
 }

 // Pre order root -->left --> right
 public void preorder(MleBinaryTree root) {
  if (root != null) {
   System.out.println(root.data);
   preorder(root.left);
   preorder(root.right);
  }
 }

 public void preorder() {
  preorder(this);
 }

 // Post order left ---> right--> root
 public void postorder(MleBinaryTree root) {
  if (root != null) {
   postorder(root.left);
   postorder(root.right);
   System.out.println(root.data);

  }
 }

 // Post order
 public void postorder() {
  postorder(this);
 }

 public static void main(String args[]) {
  MleBinaryTree mle = new MleBinaryTree(50);

  mle.insert(30);
  mle.insert(20);
  mle.insert(40);
  mle.insert(70);
  mle.insert(60);
  mle.insert(80);
  System.out.println("Inorder");
  mle.inorder();

  System.out.println("Preorder");
  mle.preorder();

  System.out.println("Postorder");
  mle.postorder();

 }
}



Output:

No comments:

Post a Comment