How do you create tree data structure ?

  1. /* Class containing left and right child of current
  2. node and data value*/
  3. class Node
  4. {
  5. int data;
  6. Node leftright;

  7. public Node(int data1)
  8. {
  9. data = data1;
  10. left = right = null;
  11. }
  12. }

  13. // A Java program to introduce Binary Tree
  14. class BinaryTree
  15. {
  16. // Root of Binary Tree
  17. Node root;

  18. // Constructors
  19. BinaryTree(int data1)
  20. {
  21. root = new Node(data1);
  22. }

  23. BinaryTree()
  24. {
  25. root = null;
  26. }

  27. public static void main(String[] args)
  28. {
  29. BinaryTree tree = new BinaryTree();

  30. /*create root*/
  31. tree.root = new Node(1);

  32. /* following is the tree after above statement
  33.  
  34.               1
  35.             /   \
  36.           null  null     */

  37. tree.root.left = new Node(2);
  38. tree.root.right = new Node(3);

  39. /* 2 and 3 become left and right children of 1
  40.                1
  41.              /   \
  42.             2      3
  43.           /    \    /  \
  44.         null null null null  */


  45. tree.root.left.left = new Node(4);
  46. tree.root.left.left.right = new Node(9);
  47.         /* 4 becomes left child of 2
  48.                     1
  49.                 /       \
  50.                2          3
  51.              /   \       /  \
  52.             4    null  null  null
  53.            /   \
  54.           null 9
  55.          */
  56. System.out.println(tree.root.right.data);
  57. }
  58. }
Output: 3

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation