Problem statement: How will you create tree in java?
- /* Class containing left and right child of current
- node and data value*/
- class Node
- {
- int data;
- Node left, right;
- public Node(int data1)
- {
- data = data1;
- left = right = null;
- }
- }
- // A Java program to introduce Binary Tree
- class BinaryTree
- {
- // Root of Binary Tree
- Node root;
- // Constructors
- BinaryTree(int data1)
- {
- root = new Node(data1);
- }
- BinaryTree()
- {
- root = null;
- }
- public static void main(String[] args)
- {
- BinaryTree tree = new BinaryTree();
- /*create root*/
- tree.root = new Node(1);
- /* following is the tree after above statement
1/ \null null */- tree.root.left = new Node(2);
- tree.root.right = new Node(3);
- /* 2 and 3 become left and right children of 1
1/ \2 3/ \ / \null null null null */- tree.root.left.left = new Node(4);
-
tree.root.left.left.right =newNode(9); /* 4 becomes left child of 21/ \2 3/ \ / \4 null null null/ \null 9*/- System.out.println(tree.root.right.data);
- }
- }
Output: 3
No comments:
Post a Comment