Monday, May 7, 2018

Tree Data structure Implementation



  1. class Node {

  2. int data;
  3. Node left;
  4. Node right;

  5. Node(int data) {
  6. this.data = data;

  7. }
  8. }

  9. public class BaseTree {
  10. public static void main(String[] args) {
  11. Node root=new Node(1);

  12. Node a1=new Node(2);
  13. Node a2=new Node(3);
  14. Node a3=new Node(4);
  15. Node a4=new Node(5);
  16. Node a5=new Node(6);
  17. Node a6=new Node(7);


  18. root.left=a1;
  19. root.right=a2;

  20. a1.left=a3;
  21. a1.right=a4;

  22. a2.left=a5;
  23. a2.right=a6;


  24. System.out.println(height(root)-1);
  25. //preOrder(root);
  26. //inOrder(root);
  27. //postOrder(root);
  28. //System.out.println(root.left.right.data);
  29. //System.out.println(root.data);
  30. //System.out.println(root.left.data);
  31. //System.out.println(root.left.left.data);
  32. //System.out.println(root.left.right.data);
  33. //System.out.println(root.right.left.data);
  34. //System.out.println(root.right.right.data);
  35. }

  36. public static void preOrder(Node root){
  37. if(root==null){
  38. return;
  39. }
  40. System.out.println(root.data);
  41. preOrder(root.left);// root=root.left;root=root.left.left;
  42. preOrder(root.right);
  43. }
  44. public static void inOrder(Node root){
  45. if(root==null){
  46. return;
  47. }
  48. preOrder(root.left);
  49. System.out.println(root.data);
  50. preOrder(root.right);
  51. }
  52. public static void postOrder(Node root){
  53. if(root==null){
  54. return;
  55. }
  56. preOrder(root.left);
  57. preOrder(root.right);
  58. System.out.println(root.data);
  59. }


  60. public static int height(Node root){
  61. if(root==null){
  62. return 0;
  63. }
  64. else
  65.     {
  66.         int lDepth = height(root.left);
  67.         int rDepth = height(root.right);

  68.         if (lDepth > rDepth)
  69.             return (lDepth + 1);
  70.          else
  71.             return (rDepth + 1);
  72.     }
  73. }
}

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...