Wednesday, 2 May 2018

3. Java Program to create Binary Tree

7. Program for Binary Tree
1.     Below java program creates the below Binary Tree
                              1
                        /       \
                       2          3
                     /   \       /  \
                    4    null null null
                   /   \
                             null null

public class Node {

     Object data;
     Node leftNode;
     Node rightNode;

     public Node(Object data) {
          this.data = data;
          this.leftNode = null;
          this.rightNode = null;
     }

     public Node(Object data, Node left, Node right) {
          this.data = data;
          this.leftNode = left;
          this.rightNode = right;
     }
}


public class BinaryTree {

     Node root;

     public BinaryTree(Object data) {
          root = new Node(data);
     }
}



public class Main {

     public static void main(String[] args) {
          BinaryTree tree = new BinaryTree(1);
          tree.root.leftNode = new Node(9);
          tree.root.rightNode = new Node(11);
          tree.root.leftNode.leftNode = new Node(4);
     }

}







2. Why Trees

5. Why Tree?
1.     One reason to use trees might be because you want to store information that naturally forms a hierarchy.
2.     For example, File system in computer, family hierarchy (grandparents, parents, children and so on), Hierarchy of job positions (Senior Project manager, project manager, employees) and there can be many others.                            
           
3.     If we organize tree in ordered way (BST) than we can search for a given key in very less time compared to Linked List and similar to ordered arrays search.
4.     Also, we can insert, delete the key in very faster than arrays, lined list.
5.     Like Linked Lists and unlike Arrays, Pointer implementation of trees don’t have an upper limit on number of nodes as nodes are linked using pointers.
6.     A tree can be viewed as a recursive data structure. Recursive means that something is defined in terms of itself. Here, this means that trees are made up of subtrees.

6. Where we use Tree?
1.     Manipulate hierarchical data.
2.     Make information easy to search.
3.     Manipulate sorted lists of data.
4.     As a workflow for compositing digital images for visual effects.
5.     Router algorithms.




3. Java Program to create Binary Tree