Tuesday, June 14, 2016

Binary Trees example in java

Why use Binary Trees?

Because,it combines the advantage  of two other structures: an ordered array and linked list.you can search a tree quickly,as you can ordered array and you can also insert , delete items quickly as you can with linked list.Lets explore why?.

  1. Slow Insertion in an Ordered Array 
  2. Slow Searching in a Linked List
It would be nice if there were a data structure with the quick insertion and deletion of a linked list and also the quick searching of an ordered array.

Tree Terminology:
  1. Path-Thinking of someone walking from node to node along the edges that connect them.
  2. Root-The node at the top of the tree is called Root.
  3. Parent-Any node except the root has exactly one edge running upward to another node.
  4. Child-Any node may have one or more lines running downward to other nodes.
  5. Leaf-A node that has no children is called Leaf.
  6. Sub Tree-Any node may be considered to be the root of a subtree,which cinsists of its children and its childrens children.
  7. Visiting-A node is visited when program control arrives at the node.
  8. Traversing-To visit all the nodes in some specified order.
  9. Levels-The level of a particular node refers to how many generations the node is from the root.
  10. Keys-One data field in an object is usually designated a key value.This value is used to search for the item.
Binary Trees
If every node in a tree can have at most two children,the tree is called a binary tree.

Representing the tree in java code:

The Node class

First we need a class of node objects.these objects contain the data representing the objects being stored and also references to each of the nodes two children.

class Node
{
  int iData;
  double fData;
  Node leftChild;
  Node rightChild;

 public void displayNode()
 {
    // display node
 }
}

The Tree Class


class Tree
{
  private Node root;
  
  public void find(int key)
  {
  }
  public void insert(int id,double dd)
  {
  }
  public void delete(int id)
  {  
  }

  // various other methods
}



No comments: