Wednesday, June 20, 2018

How do you create tree data structure ?

Problem statement: How will you create tree in java?
  1. /* Class containing left and right child of current
  2. node and data value*/
  3. class Node
  4. {
  5. int data;
  6. Node left, right;

  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

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...