mjain

BinaryTree

Jun 7th, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 28.58 KB | None | 0 0
  1. package testrun;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Comparator;
  5. import java.util.HashMap;
  6. import java.util.LinkedList;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.Map.Entry;
  10. import java.util.PriorityQueue;
  11. import java.util.Stack;
  12. import java.util.TreeMap;
  13.  
  14. public class BinaryTree {
  15.     public static int maxLevel = -1;
  16.     public static int maxSum   = 0;
  17.  
  18.     public static Integer maxPathSum(Node root) {
  19.  
  20.         maxSumUtil(root);
  21.         return maxSum;
  22.     }
  23.  
  24.     public static Integer maxSumUtil(Node root) {
  25.         if (root == null) {
  26.             return 0;
  27.         }
  28.         int l = maxSumUtil(root.left);
  29.         int r = maxSumUtil(root.right);
  30.         int max1 = Math.max(Math.max(l, r) + root.data, root.data);
  31.         int max2 = Math.max(max1, l + r + root.data);
  32.         maxSum = Math.max(maxSum, max2);
  33.         return max1;
  34.     }
  35.  
  36.     public static void main(String[] arg) {
  37.  
  38.         /* Let us construct the tree shown in above diagram */
  39.         Node root = new Node(20);
  40.         root.left = new Node(8);
  41.         root.right = new Node(22);
  42.         root.left.left = new Node(4);
  43.         root.left.right = new Node(12);
  44.         root.left.right.left = new Node(10);
  45.         root.left.right.right = new Node(14);
  46.         Node target = root.left.right;
  47.         printNodesAtKthDisttanceFromGivenNode(root, target, 2);
  48.  
  49.         // timeToBurnTreeFromGivenNode(root, 25);
  50.         // Node parent = findLCA(root, 3, 4);
  51.         // System.out.println("Parent of 3 and 4 is: " + parent.data);
  52.         //
  53.         // int height = height(root, 0);
  54.         // System.out.println("height: " + height);
  55.         // System.out.println("Left view of tree is");
  56.         // printLeftView(root, 0);
  57.         // maxLevel = -1;
  58.         // System.out.println("right view of tree is");
  59.         // printRightView(root, 0);
  60.         // val = new Values();
  61.         // printVerticalOrderByMap(root);
  62.         // printTopView(root);
  63.         // prinBottomView(root);
  64.         // printLevelOrder(root);
  65.         // printLevelOrderSpiralWith2Stacks(root);
  66.         // convertTreeToDLL(root);
  67.         // int norOfLeaves = getNoOfLeafNodes(root);
  68.         // System.out.print("No of leaves: " + norOfLeaves);
  69.     }
  70.  
  71.     public static class Sum {
  72.         int sum = 0;
  73.     }
  74.  
  75.     static void printkdistanceNodeDown(Node node, int k) {
  76.         if (node == null || k < 0)
  77.             return;
  78.  
  79.         if (k == 0) {
  80.             System.out.print(node.data);
  81.             System.out.println("");
  82.             return;
  83.         }
  84.  
  85.         // Recur for left and right subtrees
  86.         printkdistanceNodeDown(node.left, k - 1);
  87.         printkdistanceNodeDown(node.right, k - 1);
  88.     }
  89.  
  90.     public static int printNodesAtKthDisttanceFromGivenNode(Node node, Node targetNode, int k) {
  91.         if (node == null) {
  92.             return -1;
  93.         }
  94.         // if target is same as root,only print node down at distance k
  95.         if (node == targetNode) {
  96.             printkdistanceNodeDown(node, k);
  97.             return 0;
  98.         }
  99.         int distanceFromLeft = printNodesAtKthDisttanceFromGivenNode(node.left, targetNode, k);
  100.         if (distanceFromLeft != -1) {
  101.             // here node found in left tree
  102.             if (distanceFromLeft + 1 == k) {
  103.                 System.out.print(node.data);
  104.                 System.out.println("");
  105.             } else {
  106.                 // else go to right tree with k-distanceinleft-2;
  107.                 printkdistanceNodeDown(node.right, k - distanceFromLeft - 2);
  108.             }
  109.             return 1 + distanceFromLeft;
  110.         }
  111.         int distanceFromRight = printNodesAtKthDisttanceFromGivenNode(node.right, targetNode, k);
  112.         if (distanceFromRight != -1) {
  113.             // here node found in left tree
  114.             if (distanceFromRight + 1 == k) {
  115.                 System.out.print(node.data);
  116.                 System.out.println("");
  117.             } else {
  118.                 // else go to left tree with k-distanceFromRight-2;
  119.                 printkdistanceNodeDown(node.left, k - distanceFromRight - 2);
  120.             }
  121.             return 1 + distanceFromRight;
  122.         }
  123.         return -1;
  124.     }
  125.  
  126.     public static void sumOFSmallesetKthNodeInBST(Node root, int k, int count, Sum sum) {
  127.         if (root == null) {
  128.             return;
  129.         }
  130.         sumOFSmallesetKthNodeInBST(root.left, k, count + 1, sum);
  131.         if (count < k) {
  132.             sum.sum += root.data;
  133.         }
  134.         sumOFSmallesetKthNodeInBST(root.right, k, count + 1, sum);
  135.     }
  136.  
  137.     public static boolean isHeightBalanced(Node root) {
  138.         if (root == null) {
  139.             return true;
  140.         }
  141.         if (Math.abs(height(root.left) - height(root.right)) <= 1 && isHeightBalanced(root.left)
  142.                 && isHeightBalanced(root.right)) {
  143.             return true;
  144.         }
  145.         return false;
  146.     }
  147.  
  148.     public boolean checkBSTUtil(Node root, int min, int max) {
  149.         if (root == null) {
  150.             return true;
  151.         }
  152.         if (root.data < min || root.data > max) {
  153.             return false;
  154.         }
  155.         return checkBSTUtil(root.left, min, root.data - 1) && checkBSTUtil(root.right, root.data + 1, max);
  156.     }
  157.  
  158.     public static class Values {
  159.         int min, max;
  160.     }
  161.  
  162.     public static class Queue {
  163.         Node node;
  164.         int  level;
  165.  
  166.         public Queue(Node node, int level) {
  167.             super();
  168.             this.node = node;
  169.             this.level = level;
  170.         }
  171.     }
  172.  
  173.     public static void printTopView(Node root) {
  174.         System.out.println("Top view of tree");
  175.         Queue queue = new Queue(root, 0);
  176.         // tree map taken as we need in sorted order of horizontal distance
  177.         Map<Integer, Node> map = new TreeMap<Integer, BinaryTree.Node>();
  178.         LinkedList<Queue> q = new LinkedList<BinaryTree.Queue>();
  179.         q.add(queue);
  180.         while (!q.isEmpty()) {
  181.             Queue curNode = q.poll();
  182.             if (curNode != null) {
  183.                 if (!map.containsKey(curNode.level)) {
  184.                     map.put(curNode.level, curNode.node);
  185.                 }
  186.                 if (curNode.node.left != null) {
  187.                     q.add(new Queue(curNode.node.left, curNode.level - 1));
  188.                 }
  189.                 if (curNode.node.right != null) {
  190.                     q.add(new Queue(curNode.node.right, curNode.level + 1));
  191.                 }
  192.             }
  193.         }
  194.         for (int key : map.keySet()) {
  195.             System.out.print(map.get(key).data + ",");
  196.         }
  197.  
  198.     }
  199.  
  200.     public static void prinBottomView(Node root) {
  201.         System.out.println("Bottom view of tree");
  202.         Queue queue = new Queue(root, 0);
  203.         // tree map taken as we need in sorted order of horizontal distance
  204.         Map<Integer, Node> map = new TreeMap<Integer, BinaryTree.Node>();
  205.         LinkedList<Queue> q = new LinkedList<BinaryTree.Queue>();
  206.         q.add(queue);
  207.         while (!q.isEmpty()) {
  208.             Queue curNode = q.poll();
  209.             if (curNode != null) {
  210.                 // replace node everytime we get a new one at given level as we
  211.                 // nned last one from particulat HD
  212.                 map.put(curNode.level, curNode.node);
  213.                 if (curNode.node.left != null) {
  214.                     q.add(new Queue(curNode.node.left, curNode.level - 1));
  215.                 }
  216.                 if (curNode.node.right != null) {
  217.                     q.add(new Queue(curNode.node.right, curNode.level + 1));
  218.                 }
  219.             }
  220.         }
  221.         for (int key : map.keySet()) {
  222.             System.out.print(map.get(key).data + ",");
  223.         }
  224.  
  225.     }
  226.  
  227.     public static void getMinMaxHorizontalDistances(Node root, Values min, Values max, int hd) {
  228.         if (root == null) {
  229.             return;
  230.         }
  231.         if (hd < min.min) {
  232.             min.min = hd;
  233.         } else if (hd > max.max) {
  234.             max.max = hd;
  235.         }
  236.         getMinMaxHorizontalDistances(root.left, min, max, hd - 1);
  237.         getMinMaxHorizontalDistances(root.right, min, max, hd + 1);
  238.     }
  239.  
  240.     public static void printVerticalLineWiseNodes(Node root, int curLine, int hd) {
  241.         if (root == null) {
  242.             return;
  243.         }
  244.         if (curLine == hd) {
  245.             System.out.print(root.data + ",");
  246.         }
  247.  
  248.         printVerticalLineWiseNodes(root.left, curLine, hd - 1);
  249.         printVerticalLineWiseNodes(root.right, curLine, hd + 1);
  250.  
  251.     }
  252.  
  253.     public static void printVerticalOrder(Node root, Values val) {
  254.         getMinMaxHorizontalDistances(root, val, val, 0);
  255.         for (int curHD = val.min; curHD <= val.max; curHD++) {
  256.             printVerticalLineWiseNodes(root, curHD, 0);
  257.             System.out.println("");
  258.         }
  259.     }
  260.  
  261.     public static void populateMap(Node root, TreeMap<Integer, List<Node>> map, int hd) {
  262.         if (root == null) {
  263.             return;
  264.         }
  265.         if (map.containsKey(hd)) {
  266.             map.get(hd).add(root);
  267.         } else {
  268.             List<Node> list = new ArrayList<BinaryTree.Node>();
  269.             list.add(root);
  270.             map.put(hd, list);
  271.         }
  272.         populateMap(root.left, map, hd - 1);
  273.         populateMap(root.right, map, hd + 1);
  274.     }
  275.  
  276.     public static void printVerticalOrderByMap(Node root) {
  277.         TreeMap<Integer, List<Node>> map = new TreeMap<Integer, List<Node>>();
  278.         populateMap(root, map, 0);
  279.         for (int key : map.keySet()) {
  280.             for (Node node : map.get(key)) {
  281.                 System.out.print(node.data + ",");
  282.             }
  283.             System.out.println("");
  284.         }
  285.     }
  286.  
  287.     public static int height(Node root) {
  288.         if (root == null) {
  289.             return -1;
  290.         }
  291.         int lh = height(root.left);
  292.         int rh = height(root.right);
  293.         return Math.max(lh, rh) + 1;
  294.     }
  295.  
  296.     public static void printLeftView(Node root, int level) {
  297.         if (root == null) {
  298.             return;
  299.         }
  300.         if (level > maxLevel) {
  301.             System.out.println(root.data);
  302.             maxLevel = level;
  303.         }
  304.  
  305.         printLeftView(root.left, level + 1);
  306.         printLeftView(root.right, level + 1);
  307.     }
  308.  
  309.     public static void printRightView(Node root, int level) {
  310.         if (root == null) {
  311.             return;
  312.         }
  313.         if (level > maxLevel) {
  314.             System.out.println(root.data);
  315.             maxLevel = level;
  316.         }
  317.  
  318.         printRightView(root.right, level + 1);
  319.         printRightView(root.left, level + 1);
  320.     }
  321.  
  322.     public static void printLevelOrder(Node root) {
  323.         LinkedList<Node> queue = new LinkedList<BinaryTree.Node>();
  324.         queue.add(root);
  325.         while (!queue.isEmpty()) {
  326.             Node curNode = queue.poll();
  327.             if (curNode != null) {
  328.                 System.out.print(curNode.data + " ");
  329.                 if (curNode.left != null) {
  330.                     queue.add(curNode.left);
  331.                 }
  332.                 if (curNode.right != null) {
  333.                     queue.add(curNode.right);
  334.                 }
  335.             }
  336.         }
  337.     }
  338.  
  339.     public static boolean areMirror(Node root1, Node root2) {
  340.         if (root1 == null && root2 == null) {
  341.             return true;
  342.         }
  343.         if ((root1 == null && root2 != null) || (root1 != null && root2 == null)) {
  344.             return false;
  345.         }
  346.  
  347.         java.util.Queue<Node> queue = new LinkedList<BinaryTree.Node>();
  348.         queue.add(root1);
  349.         queue.add(root2);
  350.  
  351.         while (!queue.isEmpty()) {
  352.             Node a = queue.peek();
  353.             queue.poll();
  354.             Node b = queue.peek();
  355.             queue.poll();
  356.             if (a.data != b.data) {
  357.                 return false;
  358.             }
  359.             if (a.left != null && b.right != null) {
  360.                 queue.add(a.left);
  361.                 queue.add(b.right);
  362.             }
  363.             if (a.left != null || b.right != null) {
  364.                 return false;
  365.             }
  366.             if (a.right != null && b.left != null) {
  367.                 queue.add(a.right);
  368.                 queue.add(b.left);
  369.             }
  370.             if (a.right != null || b.left != null) {
  371.                 return false;
  372.             }
  373.         }
  374.  
  375.         return true;
  376.     }
  377.  
  378.     public static void printLevelOrderSpiralWith2Stacks(Node root) {
  379.         Stack<Node> s1 = new Stack<BinaryTree.Node>();
  380.         Stack<Node> s2 = new Stack<BinaryTree.Node>();
  381.         s1.add(root);
  382.         while (!s1.isEmpty() || !s2.isEmpty()) {
  383.             while (!s1.isEmpty()) {
  384.                 Node curTop = s1.peek();
  385.                 s1.pop();
  386.                 System.out.print(curTop.data + ",");
  387.                 if (curTop.right != null) {
  388.                     s2.add(curTop.right);
  389.                 }
  390.                 if (curTop.left != null) {
  391.                     s2.add(curTop.left);
  392.                 }
  393.             }
  394.             while (!s2.isEmpty()) {
  395.                 Node curTop = s2.peek();
  396.                 s2.pop();
  397.                 System.out.print(curTop.data + ",");
  398.                 if (curTop.left != null) {
  399.                     s1.add(curTop.left);
  400.                 }
  401.                 if (curTop.right != null) {
  402.                     s1.add(curTop.right);
  403.                 }
  404.             }
  405.         }
  406.     }
  407.  
  408.     public void connectNodesAtSameLevel(Node root) {
  409.         java.util.Queue<Node> q = new LinkedList<Node>();
  410.         q.add(root);
  411.         q.add(null);
  412.         while (!q.isEmpty()) {
  413.             Node curNode = q.peek();
  414.             q.remove();
  415.             if (curNode != null) {
  416.                 curNode.next = q.peek();
  417.  
  418.                 if (curNode.left != null) {
  419.                     q.add(curNode.left);
  420.                 }
  421.                 if (curNode.right != null) {
  422.                     q.add(curNode.right);
  423.                 }
  424.             }
  425.             if (!q.isEmpty()) {
  426.                 q.add(null);
  427.             }
  428.         }
  429.     }
  430.  
  431.     public static Node bintree2listUtil(Node node) {
  432.         if (node == null)
  433.             return node;
  434.  
  435.         if (node.left != null) {
  436.             Node left = bintree2listUtil(node.left);
  437.             for (; left.right != null; left = left.right)
  438.                 ;
  439.             left.right = node;
  440.             node.left = left;
  441.         }
  442.  
  443.         if (node.right != null) {
  444.             Node right = bintree2listUtil(node.right);
  445.             for (; right.left != null; right = right.left)
  446.                 ;
  447.             right.left = node;
  448.             node.right = right;
  449.         }
  450.         return node;
  451.     }
  452.  
  453.     public static Node convertTreeToDLL(Node root) {
  454.         System.out.println("DLL:");
  455.         if (root == null) {
  456.             return root;
  457.         }
  458.         Node node = bintree2listUtil(root);
  459.         while (node.left != null) {
  460.             node = node.left;
  461.         }
  462.         while (node != null) {
  463.             System.out.print(node.data + " ");
  464.             node = node.right;
  465.         }
  466.         return node;
  467.     }
  468.  
  469.     public static boolean isIdenticalTreeRecursive(Node root1, Node root2) {
  470.         if (root1 == null && root2 == null) {
  471.             return true;
  472.         }
  473.         if (root1 != null && root2 != null) {
  474.             return root1.data == root2.data && isIdenticalTreeRecursive(root1.left, root2.left)
  475.                     && isIdenticalTreeRecursive(root1.right, root2.right);
  476.         }
  477.         return false;
  478.     }
  479.  
  480.     public static boolean isSubTree(Node bigTree, Node smallTree) {
  481.         if (bigTree == null) {
  482.             return false;
  483.         }
  484.         if (smallTree == null) {
  485.             return true;
  486.         }
  487.         boolean isSame = isIdenticalTreeRecursive(bigTree, smallTree);
  488.         if (isSame) {
  489.             return true;
  490.         }
  491.  
  492.         return isSubTree(bigTree.left, smallTree) || isSubTree(bigTree.right, smallTree)
  493.                 || isSubTree(bigTree, smallTree);
  494.  
  495.     }
  496.  
  497.     public static boolean isIdenticalIterative(Node root1, Node root2) {
  498.         if (root1 == null && root2 == null) {
  499.             return true;
  500.         }
  501.         java.util.Queue<Node> queue1 = new LinkedList<BinaryTree.Node>();
  502.         java.util.Queue<Node> queue2 = new LinkedList<BinaryTree.Node>();
  503.         queue1.add(root1);
  504.         queue2.add(root2);
  505.         while (!queue1.isEmpty() && !queue2.isEmpty()) {
  506.             Node n1 = queue1.peek();
  507.             Node n2 = queue2.peek();
  508.             queue1.remove();
  509.             queue2.remove();
  510.             if (n1 != null && n2 != null) {
  511.                 if (n1.data != n2.data) {
  512.                     return false;
  513.                 }
  514.                 if (n1.left != null && n2.left != null) {
  515.                     queue1.add(n1.left);
  516.                     queue2.add(n2.left);
  517.                 }
  518.                 if (n1.left != null || n2.left != null) {
  519.                     return false;
  520.                 }
  521.                 if (n1.right != null && n2.right != null) {
  522.                     queue1.add(n1.right);
  523.                     queue2.add(n2.right);
  524.                 }
  525.                 if (n1.right != null || n2.right != null) {
  526.                     return false;
  527.                 }
  528.             }
  529.         }
  530.         return true;
  531.     }
  532.  
  533.     public int getDiameterN2(Node root) {
  534.         if (root == null) {
  535.             return 0;
  536.         }
  537.         int lH = height(root.left);
  538.         int rH = height(root.right);
  539.         int leftD = getDiameterN2(root.left);
  540.         int rightD = getDiameterN2(root.right);
  541.         return Math.max(Math.max(leftD, rightD), (lH + rH + 1));
  542.     }
  543.  
  544.     public static class Height {
  545.         int h;
  546.     }
  547.  
  548.     public static int diameterWithCalculateHeightRecurs(Node root, Height height) {
  549.         Height lh = new Height(), rh = new Height();
  550.         if (root == null) {
  551.             height.h = 0;
  552.             return 0;
  553.         }
  554.         int leftDia = diameterWithCalculateHeightRecurs(root.left, lh);
  555.         int rightDia = diameterWithCalculateHeightRecurs(root.right, rh);
  556.         height.h = Math.max(lh.h, rh.h) + 1;
  557.         return Math.max(Math.max(leftDia, rightDia), lh.h + rh.h + 1);
  558.     }
  559.  
  560.     public static int getNoOfLeafNodes(Node root) {
  561.         if (root == null) {
  562.             return 0;
  563.         }
  564.         if (root.left == null && root.right == null) {
  565.             return 1;
  566.         }
  567.         return getNoOfLeafNodes(root.left) + getNoOfLeafNodes(root.right);
  568.     }
  569.  
  570.     public static int rootToLeafMaxSum(Node root) {
  571.         if (root == null) {
  572.             return 0;
  573.         }
  574.         int leftSum = rootToLeafMaxSum(root.left);
  575.         int rightSum = rootToLeafMaxSum(root.right);
  576.         return Math.max(leftSum, rightSum) + root.data;
  577.     }
  578.  
  579.     public static void diagonalTraversalRecursiveUtil(Node root, HashMap<Integer, List<Integer>> map, int distance) {
  580.         if (root == null) {
  581.             return;
  582.         }
  583.         if (map.containsKey(distance)) {
  584.             map.get(distance).add(root.data);
  585.         } else {
  586.             List<Integer> list = new ArrayList<Integer>();
  587.             list.add(root.data);
  588.             map.put(distance, list);
  589.         }
  590.         // vertical distance increases for left child
  591.         diagonalTraversalRecursiveUtil(root.left, map, distance + 1);
  592.         // vertical distance remains same for right child
  593.         diagonalTraversalRecursiveUtil(root.right, map, distance);
  594.     }
  595.  
  596.     public static void diagonalTraversalRecursive(Node root) {
  597.         HashMap<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
  598.         diagonalTraversalRecursiveUtil(root, map, 0);
  599.         for (Entry<Integer, List<Integer>> entry : map.entrySet()) {
  600.             for (int i : entry.getValue()) {
  601.                 System.out.print(i + "-");
  602.             }
  603.             System.out.println();
  604.         }
  605.  
  606.     }
  607.  
  608.     public static void diagonalTraversalIterative(Node root) {
  609.         // maintain a queue for right tree
  610.  
  611.         java.util.Queue<Node> queue = new LinkedList<BinaryTree.Node>();
  612.         queue.add(root);
  613.         // add a delimiter to get the end of current diagonal
  614.         queue.add(null);
  615.         while (!queue.isEmpty()) {
  616.             Node curNode = queue.peek();
  617.             queue.remove();
  618.             // if delimiter reaches means end of current diagonal insert new
  619.             // delimiter and print new line
  620.             if (curNode == null) {
  621.                 if (queue.size() == 0) {
  622.                     return;
  623.                 }
  624.                 System.out.println();
  625.                 queue.add(null);
  626.             } else {
  627.                 while (curNode != null) {
  628.                     System.out.print(curNode.data + "-");
  629.                     // if left child is present
  630.                     // add into queue
  631.                     if (curNode.left != null) {
  632.                         queue.add(curNode.left);
  633.                     }
  634.  
  635.                     curNode = curNode.right;
  636.                 }
  637.             }
  638.         }
  639.     }
  640.  
  641.     public static void preOrder(Node root) {
  642.         if (root == null) {
  643.             return;
  644.         }
  645.         System.out.print(root.data + " ");
  646.         preOrder(root.left);
  647.         preOrder(root.right);
  648.  
  649.     }
  650.  
  651.     public static void postOrder(Node root) {
  652.         if (root == null) {
  653.             return;
  654.         }
  655.         postOrder(root.left);
  656.         postOrder(root.right);
  657.         System.out.print(root.data + " ");
  658.     }
  659.  
  660.     public static void inOrder(Node root) {
  661.         if (root == null) {
  662.             return;
  663.         }
  664.         inOrder(root.left);
  665.         System.out.print(root.data + " ");
  666.         inOrder(root.right);
  667.     }
  668.  
  669.     static void swapEveryKLevelUtil(Node root, int level, int k) {
  670.         if (root == null || (root.left == null && root.right == null))
  671.             return;
  672.  
  673.         if ((level + 1) % k == 0) {
  674.             Node temp = root.left;
  675.             root.left = root.right;
  676.             root.right = temp;
  677.         }
  678.  
  679.         swapEveryKLevelUtil(root.left, level + 1, k);
  680.         swapEveryKLevelUtil(root.right, level + 1, k);
  681.     }
  682.  
  683.     public static void huffmanEncoding() {
  684.         char[] charArray = { 'a', 'b', 'c', 'd', 'e', 'f' };
  685.         int[] charfreq = { 5, 9, 12, 13, 16, 45 };
  686.         PriorityQueue<Node> minHeap = new PriorityQueue<Node>(6, new HuffManComparatort());
  687.  
  688.         // create a min heap for characters
  689.         for (int index = 0; index < charArray.length; index++) {
  690.             Node n = new Node(charfreq[index]);
  691.             n.c = charArray[index];
  692.             n.left = n.right = null;
  693.             minHeap.add(n);
  694.         }
  695.         Node root = null;
  696.         // traverse the heap till single node remaining and extract first
  697.         // two,sum it and make them left and right child to new node ,insert
  698.         // into min heap again
  699.         while (minHeap.size() > 1) {
  700.             Node firstNode = minHeap.peek();
  701.             minHeap.remove();
  702.             Node secondNode = minHeap.peek();
  703.             minHeap.remove();
  704.  
  705.             int newData = firstNode.data + secondNode.data;
  706.             Node temp = new Node(newData);
  707.             temp.left = firstNode;
  708.             temp.right = secondNode;
  709.             temp.c = '-';
  710.             root = temp;
  711.             minHeap.add(temp);
  712.         }
  713.         // print the huffman encoding
  714.         printHuffmanEncoding(root, "");
  715.  
  716.     }
  717.  
  718.     public static void printHuffmanEncoding(Node root, String s) {
  719.         if (root.left == null && root.right == null && Character.isLetter(root.c)) {
  720.             System.out.println(root.c + ":" + s);
  721.             return;
  722.         }
  723.         printHuffmanEncoding(root.left, s + "0");
  724.         printHuffmanEncoding(root.right, s + "1");
  725.  
  726.     }
  727.  
  728.     static class HuffManComparatort implements Comparator<Node> {
  729.  
  730.         @Override
  731.         public int compare(Node o1, Node o2) {
  732.             return o1.data - o2.data;
  733.         }
  734.  
  735.     }
  736.  
  737.     public static Node removeLeavesAtLevellessThanK(Node root, int level, int k) {
  738.         if (root == null) {
  739.             return null;
  740.         }
  741.         root.left = removeLeavesAtLevellessThanK(root.left, level + 1, k);
  742.         root.right = removeLeavesAtLevellessThanK(root.right, level + 1, k);
  743.  
  744.         if (root.left == null && root.right == null && level < k) {
  745.             root = null;
  746.         }
  747.         return root;
  748.     }
  749.  
  750.     public static class Level {
  751.         int maxlevel = 0;
  752.     }
  753.  
  754.     static Node deepestLeaf = null;
  755.  
  756.     public static void deepestLeafNodeInTree(Node root, int curLevel, Level level) {
  757.         if (root == null) {
  758.             return;
  759.         }
  760.         if (root.left == null && root.right == null && curLevel > level.maxlevel) {
  761.             level.maxlevel = curLevel;
  762.             deepestLeaf = root;
  763.         }
  764.         deepestLeafNodeInTree(root.left, curLevel + 1, level);
  765.         deepestLeafNodeInTree(root.right, curLevel + 1, level);
  766.     }
  767.  
  768.     public static int getLevelOfKey(Node root, int key, int level) {
  769.         if (root == null) {
  770.             return -1;
  771.         }
  772.         if (root.data == key) {
  773.             return level;
  774.         }
  775.         int l = getLevelOfKey(root.left, key, level + 1);
  776.         return (l == -1 ? getLevelOfKey(root.right, key, level + 1) : l);
  777.     }
  778.  
  779.     public static Node findLCA(Node root, int first, int second) {
  780.         if (root == null) {
  781.             return null;
  782.         }
  783.         if (root.data == first || root.data == second) {
  784.             return root;
  785.         }
  786.         Node retLeft = findLCA(root.left, first, second);
  787.         Node retRight = findLCA(root.right, first, second);
  788.         if (retLeft != null && retRight != null) {
  789.             return root;
  790.         }
  791.         return retLeft != null ? retLeft : retRight;
  792.     }
  793.  
  794.     public static void timeToBurnTreeFromGivenNode(Node root, int dataOfGiveNode) {
  795.         int levelOfKeyInleftTree = getLevelOfKey(root.left, dataOfGiveNode, 1);
  796.         int levelOfKeyInRightTree = getLevelOfKey(root.right, dataOfGiveNode, 1);
  797.         Level levelOfDeepestLeaf = new Level();
  798.         int depthOfStartingNode = -1;
  799.         int depthOfLeafNodeAtSameSide = -1;
  800.         int depethOfOppositeSide = -1;
  801.         int depthOfCommonAncestor = -1;
  802.         // starting node found in left tree,Found the deepest leaf from left
  803.         // tree else do the same in right tree
  804.         if (levelOfKeyInleftTree > 0) {
  805.             depthOfStartingNode = levelOfKeyInleftTree;
  806.             deepestLeafNodeInTree(root.left, 1, levelOfDeepestLeaf);
  807.             depethOfOppositeSide = height(root.right) + 1;
  808.         } else if (levelOfKeyInRightTree > 0) {
  809.             depthOfStartingNode = levelOfKeyInRightTree;
  810.             deepestLeafNodeInTree(root.right, 1, levelOfDeepestLeaf);
  811.             depethOfOppositeSide = height(root.left) + 1;
  812.         }
  813.         System.out.println("depthOfStartingNode: " + depthOfStartingNode);
  814.         System.out.println("depethOfOppositeSide: " + depethOfOppositeSide);
  815.         System.out.println("depthOfLeafNodeAtSameSide: " + levelOfDeepestLeaf.maxlevel);
  816.         if (deepestLeaf != null) {
  817.             depthOfLeafNodeAtSameSide = levelOfDeepestLeaf.maxlevel;
  818.             // find common ancestor of starting node and deepest leaf of same
  819.             // side
  820.             Node commonAncestor = findLCA(root, dataOfGiveNode, deepestLeaf.data);
  821.             System.out.println("commonAncestor: " + commonAncestor.data);
  822.             depthOfCommonAncestor = getLevelOfKey(root, commonAncestor.data, 0);
  823.             System.out.println("depthOfCommonAncestor: " + depthOfCommonAncestor);
  824.         }
  825.         int timeToBurn = Math.max(
  826.                 ((depthOfLeafNodeAtSameSide - depthOfCommonAncestor) + (depthOfStartingNode - depthOfCommonAncestor)),
  827.                 (depthOfStartingNode + depethOfOppositeSide));
  828.         System.out.println("Time to burn tree: " + timeToBurn);
  829.  
  830.     }
  831.  
  832.     public static class Node {
  833.         Node left;
  834.         Node right;
  835.         int  data;
  836.         Node next;
  837.         char c;
  838.  
  839.         Node(int key) {
  840.             this.data = key;
  841.             left = null;
  842.             right = null;
  843.         }
  844.  
  845.         public Node(Node left, Node right, int data) {
  846.             super();
  847.             this.left = left;
  848.             this.right = right;
  849.             this.data = data;
  850.         }
  851.  
  852.         public Node getLeft() {
  853.             return left;
  854.         }
  855.  
  856.         public void setLeft(Node left) {
  857.             this.left = left;
  858.         }
  859.  
  860.         public Node getRight() {
  861.             return right;
  862.         }
  863.  
  864.         public void setRight(Node right) {
  865.             this.right = right;
  866.         }
  867.  
  868.         public int getData() {
  869.             return data;
  870.         }
  871.  
  872.         public void setData(int data) {
  873.             this.data = data;
  874.         }
  875.  
  876.         public Node getNext() {
  877.             return next;
  878.         }
  879.  
  880.         public void setNext(Node next) {
  881.             this.next = next;
  882.         }
  883.  
  884.     }
  885.  
  886. }
Add Comment
Please, Sign In to add comment