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);
     }

}







No comments:

Post a Comment

3. Java Program to create Binary Tree