Filip_Markoski

[ADSx] - Binary Tree Fun

Jan 18th, 2018
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 35.20 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. /**
  4.  * https://www.cs.cmu.edu/~adamchik/15-121/lectures/Trees/code/BST.java
  5.  * */
  6.  
  7. public class BinaryTreeFun {
  8.  
  9.     public static void inOrder(Node node) {
  10.         if (node == null) return;
  11.         /* L O R */
  12.         inOrder(node.left);
  13.         System.out.print(node.data + " ");
  14.         inOrder(node.right);
  15.     }
  16.  
  17.     public static void preOrder(Node node) {
  18.         if (node == null) return;
  19.         /* O L R */
  20.         System.out.print(node.data + " ");
  21.         preOrder(node.left);
  22.         preOrder(node.right);
  23.     }
  24.  
  25.     public static void postOrder(Node node) {
  26.         if (node == null) return;
  27.         /* L R O*/
  28.         postOrder(node.left);
  29.         postOrder(node.right);
  30.         System.out.print(node.data + " ");
  31.     }
  32.  
  33.     public static void zigzagOrder(Node node, int height, boolean side) {
  34.         if (node == null) return;
  35.  
  36.         if (height == 1) {
  37.             System.out.print(node.data + " ");
  38.             return;
  39.         }
  40.  
  41.         if (side) {
  42.             zigzagOrder(node.left, height - 1, side);
  43.             zigzagOrder(node.right, height - 1, side);
  44.         } else {
  45.             zigzagOrder(node.right, height - 1, side);
  46.             zigzagOrder(node.left, height - 1, side);
  47.         }
  48.     }
  49.  
  50.     public static void printZigZag(Node node) {
  51.         if (node == null) return;
  52.         int height = height(node);
  53.         boolean side = false;
  54.         System.out.println("Height: " + height);
  55.         for (int i = 1; i <= height; i++) {
  56.             System.out.printf("Level (%d): ", i);
  57.             zigzagOrder(node, i, side);
  58.             System.out.println();
  59.             side = !side;
  60.         }
  61.     }
  62.  
  63.     public static void printZigZagStack(Node node) {
  64.         /**
  65.          * Works, but prints as it reads, not as we read the tree in zigzag
  66.          * */
  67.  
  68.         if (node == null) return;
  69.         StringBuffer sb = new StringBuffer();
  70.  
  71.         Stack<Node> currentLevel = new Stack<>();
  72.         Stack<Node> nextLevel = new Stack<>();
  73.  
  74.         currentLevel.push(node);
  75.  
  76.         boolean leftToRight = true;
  77.         while (!currentLevel.isEmpty()) {
  78.             Node current = currentLevel.pop();
  79.  
  80.             if (current != null) {
  81.                 sb.append(current.data).append(" ");
  82.                 if (leftToRight) {
  83.                     if (current.right != null) nextLevel.push(current.right);
  84.                     if (current.left != null) nextLevel.push(current.left);
  85.                 } else {
  86.                     if (current.right != null) nextLevel.push(current.right);
  87.                     if (current.left != null) nextLevel.push(current.left);
  88.                 }
  89.             }
  90.  
  91.             //System.out.printf("C: %-40s N: %-40s\n", currentLevel, nextLevel);
  92.             if (currentLevel.isEmpty()) {
  93.                 leftToRight = !leftToRight;
  94.  
  95.                 while (!nextLevel.isEmpty()) {
  96.                     Node pop = nextLevel.pop();
  97.                     currentLevel.push(pop);
  98.                 }
  99.             }
  100.         }
  101.         System.out.println(sb.toString());
  102.     }
  103.  
  104.     public static void zigzagStack(Node node) {
  105.         if (node == null) return;
  106.         StringBuffer sb = new StringBuffer();
  107.  
  108.         Stack<Node> currentLevel = new Stack<>();
  109.         Stack<Node> nextLevel = new Stack<>();
  110.  
  111.         int height = height(node);
  112.  
  113.         currentLevel.push(node);
  114.  
  115.         for (int i = 0; i < height; i++) {
  116.             sb.append("\n");
  117.             if (i % 2 == 0) {
  118.  
  119.                 while (!currentLevel.isEmpty()) {
  120.                     Node current = currentLevel.pop();
  121.                     sb.append(current.data).append(" ");
  122.                     if (current.right != null) nextLevel.push(current.right);
  123.                     if (current.left != null) nextLevel.push(current.left);
  124.                 }
  125.             } else {
  126.                 while (!nextLevel.isEmpty()) {
  127.                     Node current = nextLevel.pop();
  128.                     sb.append(current.data).append(" ");
  129.                     if (current.left != null) currentLevel.push(current.left);
  130.                     if (current.right != null) currentLevel.push(current.right);
  131.                 }
  132.             }
  133.         }
  134.         System.out.println(sb.toString() + System.lineSeparator());
  135.     }
  136.  
  137.     public static int height(Node node) {
  138.         if (node == null) return 0;
  139.         return 1 + Math.max(height(node.left), height(node.right));
  140.     }
  141.  
  142.     public static int heightQueue(Node node) {
  143.         Queue<Node> queue = new LinkedList<>(); // ArrayDeque doesn't allow null values
  144.         int height = 0;
  145.         queue.add(node);
  146.         queue.add(null); // Null serves as a marker
  147.         while (!queue.isEmpty()) {
  148.             Node poll = queue.poll();
  149.             if (poll == null) {
  150.                 if (!queue.isEmpty()) {
  151.                     queue.add(null);
  152.                 }
  153.                 height++;
  154.             } else {
  155.                 if (poll.left != null) queue.add(poll.left);
  156.                 if (poll.right != null) queue.add(poll.right);
  157.             }
  158.         }
  159.         return height;
  160.     }
  161.  
  162.     public static void printNodesAtHeight(Node node, int height) {
  163.         if (node == null) return;
  164.  
  165.         if (height == 1) System.out.print(" " + node.data);
  166.         else {
  167.             printNodesAtHeight(node.left, height - 1);
  168.             printNodesAtHeight(node.right, height - 1);
  169.         }
  170.     }
  171.  
  172.     public static void levelOrder(Node node) {
  173.         System.out.print(System.lineSeparator());
  174.         int height = height(node);
  175.         for (int i = 1; i <= height; i++) {
  176.             printNodesAtHeight(node, i);
  177.             System.out.print(System.lineSeparator());
  178.         }
  179.     }
  180.  
  181.     public static void BFS(Node node) {
  182.         Queue<Node> queue = new ArrayDeque<>();
  183.         if (node == null) return;
  184.         queue.add(node);
  185.         while (!queue.isEmpty()) {
  186.             Node poll = queue.poll();
  187.             System.out.print(" " + poll.data);
  188.             if (poll.left != null) queue.add(poll.left);
  189.             if (poll.right != null) queue.add(poll.right);
  190.         }
  191.  
  192.     }
  193.  
  194.     public static void inOrderStack(Node root) {
  195.         if (root == null) return;
  196.         Stack<Node> stack = new Stack<>();
  197.  
  198.         Node node = root;
  199.  
  200.         // Go all the way to the left
  201.         while (node != null) {
  202.             stack.push(node);
  203.             node = node.left;
  204.         }
  205.  
  206.         // Leftmost will be on top of the stack
  207.         while (stack.size() > 0) {
  208.             node = stack.pop();
  209.             System.out.print(node.data + " ");
  210.             if (node.right != null) { // Check if node has a right
  211.                 node = node.right;
  212.  
  213.                 while (node != null) { // If it does got all the way to the left for that node
  214.                     stack.push(node);
  215.                     node = node.left;
  216.                 }
  217.             }
  218.         }
  219.     }
  220.  
  221.     public static void levelOrderQueue(Node node) {
  222.         Queue<Node> queue = new ArrayDeque<>();
  223.         int levelNodes = 0;
  224.         if (node == null) return;
  225.         queue.add(node);
  226.         while (!queue.isEmpty()) {
  227.             levelNodes = queue.size();
  228.             while (levelNodes > 0) {
  229.                 Node poll = queue.poll();
  230.                 System.out.print(" " + poll.data);
  231.                 if (poll.left != null) queue.add(poll.left);
  232.                 if (poll.right != null) queue.add(poll.right);
  233.                 levelNodes--;
  234.             }
  235.             System.out.print(System.lineSeparator());
  236.         }
  237.     }
  238.  
  239.     public static Map<Integer, Integer> map = new TreeMap<>();
  240.  
  241.     public static void printTopView(Node node, int level) {
  242.         if (node == null) return;
  243.  
  244.         Queue<HeightNode> queue = new ArrayDeque<>();
  245.         queue.add(new HeightNode(node, level));
  246.  
  247.         while (!queue.isEmpty()) {
  248.             HeightNode poll = queue.poll();
  249.             Node pollNode = poll.node;
  250.             int pollHeight = poll.height;
  251.  
  252.             if (map.containsKey(pollHeight)) {
  253.  
  254.             } else {
  255.                 System.out.print(pollNode.data + " ");
  256.                 map.put(pollHeight, pollNode.data);
  257.             }
  258.  
  259.             if (pollNode.left != null) {
  260.                 queue.add(new HeightNode(pollNode.left, pollHeight - 1));
  261.             }
  262.  
  263.             if (pollNode.right != null) {
  264.                 queue.add(new HeightNode(pollNode.right, pollHeight + 1));
  265.             }
  266.         }
  267.     }
  268.  
  269.     public static void printBottomView(Node node, int level) {
  270.         if (node == null) return;
  271.  
  272.         Queue<HeightNode> queue = new ArrayDeque<>();
  273.         queue.add(new HeightNode(node, level));
  274.  
  275.         while (!queue.isEmpty()) {
  276.             HeightNode poll = queue.poll();
  277.             Node pollNode = poll.node;
  278.             int pollHeight = poll.height;
  279.  
  280.             map.put(pollHeight, pollNode.data);
  281.  
  282.             if (pollNode.left != null) {
  283.                 queue.add(new HeightNode(pollNode.left, pollHeight - 1));
  284.             }
  285.  
  286.             if (pollNode.right != null) {
  287.                 queue.add(new HeightNode(pollNode.right, pollHeight + 1));
  288.             }
  289.         }
  290.     }
  291.  
  292.     public static void printBottomViewDisplay() { // print the bottom view.
  293.         Set<Integer> keys = map.keySet();
  294.         for (Integer key : keys) {
  295.             System.out.print(map.get(key) + " ");
  296.         }
  297.  
  298.     }
  299.  
  300.     public static void printTopView(Node root) {
  301.         if (root == null) return;
  302.  
  303.         Set<Integer> set = new HashSet<>();
  304.         Queue<HeightNode> queue = new ArrayDeque<>();
  305.         queue.add(new HeightNode(root, 0));
  306.  
  307.         while (!queue.isEmpty()) {
  308.             HeightNode poll = queue.poll();
  309.             int pollHeight = poll.height;
  310.             Node pollNode = poll.node;
  311.  
  312.             if (!set.contains(pollHeight)) {
  313.                 set.add(pollHeight);
  314.                 System.out.print(pollNode.data + " ");
  315.             }
  316.  
  317.             if (pollNode.left != null) queue.add(new HeightNode(pollNode.left, pollHeight - 1));
  318.             if (pollNode.right != null) queue.add(new HeightNode(pollNode.right, pollHeight + 1));
  319.         }
  320.     }
  321.  
  322.     public static void printTopViewo(Node root) {//print function
  323.         Stack<Integer> leftStack = new Stack<>();
  324.         Stack<Integer> rightStack = new Stack<>();
  325.         Node temp = root;
  326.         int counter = 0;
  327.         leftStack.push(root.data);
  328.         while (true) {
  329.             if (temp.left != null) {
  330.                 if (counter < 0) {
  331.                     counter++;
  332.                 } else {
  333.                     leftStack.push(temp.left.data);
  334.                 }
  335.                 temp = temp.left;
  336.             } else if (temp.right != null) {
  337.                 temp = temp.right;
  338.                 counter--;
  339.             } else {
  340.                 break;
  341.             }
  342.         }
  343.         counter = 0;
  344.         temp = root;
  345.         while (true) {
  346.             if (temp.right != null) {
  347.                 if (counter < 0) {
  348.                     counter++;
  349.                 } else {
  350.                     rightStack.push(temp.right.data);
  351.                 }
  352.                 temp = temp.right;
  353.             } else if (temp.left != null) {
  354.                 temp = temp.left;
  355.                 counter--;
  356.             } else {
  357.                 break;
  358.             }
  359.  
  360.         }
  361.         while (!leftStack.isEmpty()) {
  362.             System.out.print(leftStack.pop() + " ");
  363.         }
  364.         while (!rightStack.isEmpty()) {
  365.             System.out.print(rightStack.pop() + " ");
  366.         }
  367.     }
  368.  
  369.     public static void main(String args[]) {
  370.         /*
  371.                10
  372.             /     \
  373.            5       15
  374.           /  \     / \
  375.          2    7  12   20
  376.          */
  377.         Node root = new Node(10);
  378.         root.left = new Node(5);
  379.         root.right = new Node(15);
  380.         root.left.left = new Node(2);
  381.         root.left.right = new Node(7);
  382.         root.right.left = new Node(12);
  383.         root.right.right = new Node(20);
  384.         /*root.left.left.left = new Node(6);
  385.         root.left.right.right = new Node(66);*/
  386.  
  387.         Node doot = new Node(1);
  388.         doot.left = new Node(2);
  389.         doot.right = new Node(3);
  390.         doot.left.left = new Node(4);
  391.         doot.left.right = new Node(5);
  392.         doot.left.right.left = new Node(6);
  393.  
  394.         printZigZag(root);
  395.  
  396.         zigzagStack(root);
  397.  
  398.         printZigZagStack(root);
  399.  
  400.     }
  401.  
  402.     public static int sum = 0;
  403.  
  404.     public static void greaterSumTree(Node root) {
  405.         if (root == null) return;
  406.  
  407.         greaterSumTree(root.right);
  408.         int data = root.data;
  409.         root.data = sum;
  410.         sum += data;
  411.         greaterSumTree(root.left);
  412.     }
  413.  
  414.     public static Node findNodeByData(Node node, int data) {
  415.         if (node == null) return null;
  416.         if (node.data == data) return node;
  417.         Node left = findNodeByData(node.left, data);
  418.         return left == null ? findNodeByData(node.right, data) : left;
  419.     }
  420.  
  421.     public static Node LeastCommonAncestor(Node current, Node one, Node two) {
  422.         if (current == null) return null;
  423.         if (current == one || current == two) return current;
  424.  
  425.         Node left = LeastCommonAncestor(current.left, one, two);
  426.         Node right = LeastCommonAncestor(current.right, one, two);
  427.  
  428.         if (left != null && right != null) return current;
  429.  
  430.         return left == null ? right : left;
  431.     }
  432.  
  433.     public static int depth(Node current, Node target) {
  434.         if (current == null) return -1;
  435.         if (current == target) return 0;
  436.         int left = depth(current.left, target);
  437.         int right = depth(current.right, target);
  438.         if (left == -1 && right == -1) return -1;
  439.         return left == -1 ? right + 1 : left + 1;
  440.     }
  441.  
  442.     public static int distanceBetween(Node root, Node one, Node two) {
  443.         if (root == null || one == null || two == null) return -1;
  444.         Node ancestor = LeastCommonAncestor(root, one, two);
  445.         int depth1 = depth(root, ancestor);
  446.         int depth2 = depth(root, one);
  447.         int depth3 = depth(root, two);
  448.         return depth2 + depth3 - 2 * depth1;
  449.     }
  450.  
  451.     public static int successor(Node root, int data) {
  452.         Node target = findNodeByData(root, data);
  453.         if (target == null) return -1;
  454.         Node successor = null;
  455.         Node current = root;
  456.         while (current != null && current.data != target.data) {
  457.             if (current.data > target.data) {
  458.                 successor = current;
  459.                 current = current.left;
  460.             } else {
  461.                 current = current.right;
  462.             }
  463.         }
  464.         if (current == null) return -1;
  465.         if (current.right == null) return successor.data;
  466.         current = current.right;
  467.         while (current.left != null) {
  468.             current = current.left;
  469.         }
  470.         return current.data;
  471.     }
  472.  
  473.     public static Node parent(Node node, Node target) {
  474.         if (node == null) return null;
  475.         if (node.left == target || node.right == target) return node;
  476.         Node left = parent(node.left, target);
  477.         Node right = parent(node.right, target);
  478.         return left == null ? right : left;
  479.     }
  480.  
  481.     public static boolean biggerThanChildren(Node node) {
  482.         if (node == null) return true;
  483.         if (node.left != null && !(node.data >= node.left.data)) return false;
  484.         if (node.right != null && !(node.data >= node.right.data)) return false;
  485.         return biggerThanChildren(node.left) && biggerThanChildren(node.right);
  486.     }
  487.  
  488.     public static boolean isBalanced(Node node) {
  489.         /**
  490.          * https://www.geeksforgeeks.org/how-to-determine-if-a-binary-tree-is-balanced/
  491.          * */
  492.  
  493.         if (node == null) return true;
  494.  
  495.         int leftHeight = height(node.left);
  496.         int rightHeight = height(node.right);
  497.  
  498.         if (Math.abs(leftHeight - rightHeight) < 2
  499.                 && isBalanced(node.left)
  500.                 && isBalanced(node.right)) {
  501.             return true;
  502.         }
  503.         return false;
  504.     }
  505.  
  506.     public static int diameter(Node node) {
  507.         /**
  508.          * https://www.geeksforgeeks.org/diameter-of-a-binary-tree/
  509.          * */
  510.  
  511.         if (node == null) return 0;
  512.  
  513.         int leftHeight = height(node.left);
  514.         int rightHeight = height(node.right);
  515.  
  516.         int leftDiameter = diameter(node.left);
  517.         int rightDiameter = diameter(node.right);
  518.  
  519.         return Math.max(Math.max(leftDiameter, rightDiameter), leftHeight + rightHeight + 1);
  520.     }
  521.  
  522.     public static int heightEven(Node node, boolean isEven) {
  523.         /**
  524.          * https://www.geeksforgeeks.org/height-binary-tree-considering-even-level-leaves/
  525.          * call it with isEven set to false
  526.          * */
  527.  
  528.         if (node == null) return 0;
  529.  
  530.         if (node.left == null && node.right == null) {
  531.             if (isEven) return 1;
  532.             else return 0;
  533.         }
  534.  
  535.         int leftHeight = heightEven(node.left, !isEven);
  536.         int rightHeight = heightEven(node.right, !isEven);
  537.  
  538.         if (leftHeight == 0 && rightHeight == 0) return 0;
  539.  
  540.         return 1 + Math.max(leftHeight, rightHeight);
  541.     }
  542.  
  543.     public static boolean isBST(Node node, int min, int max) {
  544.         /**
  545.          * https://www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/
  546.          * */
  547.  
  548.         /* an empty tree is BST */
  549.         if (node == null) return true;
  550.  
  551.         /* false if this node violates the min/max constraints */
  552.         if (node.data < min || node.data > max) return false;
  553.  
  554.         /* otherwise check the subtrees recursively
  555.         tightening the min/max constraints */
  556.         // Allow only distinct values
  557.         return (isBST(node.left, min, node.data - 1) &&
  558.                 isBST(node.right, node.data + 1, max));
  559.     }
  560.  
  561.     public static boolean isCompleteIterative(Node node) {
  562.         /**
  563.          * https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-complete-tree-or-not/
  564.          * */
  565.  
  566.         if (node == null) return true;
  567.  
  568.         Queue<Node> queue = new LinkedList<>();
  569.  
  570.         //  A node is ‘Full Node’ if both left and right children are not empty (or not NULL).
  571.         boolean leftAndRightChildAreNotEmpty = false;
  572.  
  573.         queue.add(node);
  574.         while (!queue.isEmpty()) {
  575.             Node poll = queue.poll();
  576.  
  577.             if (poll.left != null) {
  578.                 if (leftAndRightChildAreNotEmpty) return false;
  579.                 queue.add(poll.left);
  580.             } else leftAndRightChildAreNotEmpty = true;
  581.  
  582.             if (poll.right != null) {
  583.                 if (leftAndRightChildAreNotEmpty) return false;
  584.                 queue.add(poll.right);
  585.             } else leftAndRightChildAreNotEmpty = true;
  586.         }
  587.  
  588.         return true;
  589.     }
  590.  
  591.     public static int countNodes(Node root) {
  592.         if (root == null) return (0);
  593.         return (1 + countNodes(root.left) + countNodes(root.right));
  594.     }
  595.  
  596.     /* This function checks if the binary tree is complete or not */
  597.     public static boolean isComplete(Node root, int index, int number_nodes) {
  598.         /**
  599.          * https://www.geeksforgeeks.org/check-whether-binary-tree-complete-not-set-2-recursive-solution/
  600.          * */
  601.  
  602.         // An empty tree is complete
  603.         if (root == null) return true;
  604.  
  605.         // If index assigned to current node is more than
  606.         // number of nodes in tree, then tree is not complete
  607.         if (index >= number_nodes) return false;
  608.  
  609.         // Recur for left and right subtrees
  610.         return (isComplete(root.left, 2 * index + 1, number_nodes)
  611.                 && isComplete(root.right, 2 * index + 2, number_nodes));
  612.  
  613.     }
  614.  
  615.     /**
  616.      * https://www.geeksforgeeks.org/boundary-traversal-of-binary-tree/
  617.      */
  618.  
  619.     // A simple function to print leaf nodes of a binary tree
  620.     public static void printLeaves(Node node) {
  621.         if (node != null) {
  622.             printLeaves(node.left);
  623.  
  624.             // Print it if it is a leaf node
  625.             if (node.left == null && node.right == null)
  626.                 System.out.print(node.data + " ");
  627.             printLeaves(node.right);
  628.         }
  629.     }
  630.  
  631.     // A function to print all left boundry nodes, except a leaf node.
  632.     // Print the nodes in TOP DOWN manner
  633.     public static void printBoundaryLeft(Node node) {
  634.         if (node != null) {
  635.             if (node.left != null) {
  636.                 // to ensure top down order, print the node
  637.                 // before calling itself for left subtree
  638.                 System.out.print(node.data + " ");
  639.                 printBoundaryLeft(node.left);
  640.             } else if (node.right != null) {
  641.                 System.out.print(node.data + " ");
  642.                 printBoundaryLeft(node.right);
  643.             }
  644.  
  645.             // do nothing if it is a leaf node, this way we avoid
  646.             // duplicates in output
  647.         }
  648.     }
  649.  
  650.     // A function to print all right boundry nodes, except a leaf node
  651.     // Print the nodes in BOTTOM UP manner
  652.     public static void printBoundaryRight(Node node) {
  653.         if (node != null) {
  654.             if (node.right != null) {
  655.                 // to ensure bottom up order, first call for right
  656.                 //  subtree, then print this node
  657.                 printBoundaryRight(node.right);
  658.                 System.out.print(node.data + " ");
  659.             } else if (node.left != null) {
  660.                 printBoundaryRight(node.left);
  661.                 System.out.print(node.data + " ");
  662.             }
  663.             // do nothing if it is a leaf node, this way we avoid
  664.             // duplicates in output
  665.         }
  666.     }
  667.  
  668.     // A function to do boundary traversal of a given binary tree
  669.     public static void printBoundary(Node node) {
  670.         if (node != null) {
  671.             System.out.print(node.data + " ");
  672.  
  673.             // Print the left boundary in top-down manner.
  674.             printBoundaryLeft(node.left);
  675.  
  676.             // Print all leaf nodes
  677.             printLeaves(node.left);
  678.             printLeaves(node.right);
  679.  
  680.             // Print the right boundary in bottom-up manner
  681.             printBoundaryRight(node.right);
  682.         }
  683.     }
  684.  
  685. }
  686.  
  687. class Node {
  688.     int data;
  689.     Node left;
  690.     Node right;
  691.  
  692.     public Node(int data) {
  693.         this.data = data;
  694.         this.left = null;
  695.         this.right = null;
  696.     }
  697.  
  698.     @Override
  699.     public String toString() {
  700.         return String.format("%d ", data);
  701.     }
  702. }
  703.  
  704. class HeightNode {
  705.     Node node;
  706.     int height;
  707.  
  708.     public HeightNode(Node node, int height) {
  709.         this.node = node;
  710.         this.height = height;
  711.     }
  712. }
  713.  
  714. class BTree<E> {
  715.  
  716.     /**
  717.      * Lab 9: 2 for threaded tree
  718.      * */
  719. /*
  720.     public static boolean check(BTree<Integer> tree) {
  721.  
  722.         BNode<Integer> current = tree.head.left;
  723.  
  724.         while (current.ltag == '+')
  725.             current = current.left;
  726.  
  727.         BNode<Integer> succ = tree.successorInorder(current);
  728.  
  729.         while (succ != tree.head) {
  730.             if ((succ.info - current.info) != 1){
  731.                 return false;
  732.             }
  733.  
  734.             current = succ;
  735.             succ = tree.successorInorder(current);
  736.         }
  737.         return true;
  738.     }
  739. */
  740.  
  741.     /**
  742.      * Lab 7: 3
  743.      */
  744.     public BNode<E> find(BNode<E> temp, E elem) {
  745.  
  746.         BNode<E> result = null;
  747.  
  748.         if (temp == null) return null;
  749.         if (temp.info.equals(elem)) return temp;
  750.         if (temp.left != null) result = find(temp.left, elem);
  751.         if (result == null) result = find(temp.right, elem);
  752.  
  753.         return result;
  754.     }
  755.  
  756.     public int sumLeft(BNode<? extends Number> node, BNode<? extends Number> root) {
  757.         if (node == null) return 0;
  758.  
  759.         if (node.info.intValue() < root.info.intValue()) {
  760.             return sumLeft(node.left, root) + sumLeft(node.right, root) + node.info.intValue();
  761.         }
  762.         return sumLeft(node.left, root) + sumLeft(node.right, root);
  763.     }
  764.  
  765.     public int sumRight(BNode<? extends Number> node, BNode<? extends Number> root) {
  766.         if (node == null) return 0;
  767.  
  768.         if (node.info.intValue() > root.info.intValue())
  769.             return sumRight(node.left, root) + sumRight(node.right, root) + node.info.intValue();
  770.         return sumRight(node.left, root) + sumRight(node.right, root);
  771.     }
  772.  
  773.     /**
  774.      * Lab 7: 2
  775.      */
  776.     public void PreorderNonRecursive() {
  777.         Stack<BNode<E>> stack = new Stack<>();
  778.         BNode<E> current = root;
  779.  
  780.         /* Root Left Right */
  781.  
  782.         while (true) {
  783.             while (current != null) {
  784.                 System.out.print(current.info + " ");
  785.                 stack.push(current);
  786.                 current = current.left;
  787.             }
  788.  
  789.             if (stack.isEmpty()) break;
  790.  
  791.             /* Restart */
  792.             current = stack.pop();
  793.             current = current.right;
  794.         }
  795.     }
  796.  
  797.     public BNode<E> root;
  798.  
  799.     public BTree() {
  800.         root = null;
  801.     }
  802.  
  803.     public BTree(E info) {
  804.         root = new BNode<E>(info);
  805.     }
  806.  
  807.     public void makeRoot(E elem) {
  808.         root = new BNode<E>(elem);
  809.     }
  810.  
  811.     public BNode<E> addChild(BNode<E> node, int where, E elem) {
  812.  
  813.         BNode<E> tmp = new BNode<E>(elem);
  814.  
  815.         if (where == BNode.LEFT) {
  816.             if (node.left != null)  // veke postoi element
  817.                 return null;
  818.             node.left = tmp;
  819.         } else {
  820.             if (node.right != null) // veke postoi element
  821.                 return null;
  822.             node.right = tmp;
  823.         }
  824.  
  825.         return tmp;
  826.     }
  827.  
  828.     public void inorder() {
  829.         System.out.print("INORDER: ");
  830.         inorderR(root);
  831.         System.out.println();
  832.     }
  833.  
  834.     public void inorderR(BNode<E> n) {
  835.         if (n != null) {
  836.             inorderR(n.left);
  837.             System.out.print(n.info.toString() + " ");
  838.             inorderR(n.right);
  839.         }
  840.     }
  841.  
  842.     public void preorder() {
  843.         System.out.print("PREORDER: ");
  844.         preorderR(root);
  845.         System.out.println();
  846.     }
  847.  
  848.     public void preorderR(BNode<E> n) {
  849.         if (n != null) {
  850.             System.out.print(n.info.toString() + " ");
  851.             preorderR(n.left);
  852.             preorderR(n.right);
  853.         }
  854.     }
  855.  
  856.     public void postorder() {
  857.         System.out.print("POSTORDER: ");
  858.         postorderR(root);
  859.         System.out.println();
  860.     }
  861.  
  862.     public void postorderR(BNode<E> n) {
  863.         if (n != null) {
  864.             postorderR(n.left);
  865.             postorderR(n.right);
  866.             System.out.print(n.info.toString() + " ");
  867.         }
  868.     }
  869.  
  870.     public void inorderNonRecursive() {
  871.         Stack<BNode<E>> s = new Stack<BNode<E>>();
  872.         BNode<E> p = root;
  873.         System.out.print("INORDER (nonrecursive): ");
  874.  
  875.         while (true) {
  876.             // pridvizuvanje do kraj vo leva nasoka pri sto site koreni
  877.             // na potstebla se dodavaat vo magacin za podocnezna obrabotka
  878.             while (p != null) {
  879.                 s.push(p);
  880.                 p = p.left;
  881.             }
  882.  
  883.             // ako magacinot e prazen znaci deka stebloto e celosno izminato
  884.             if (s.isEmpty())
  885.                 break;
  886.  
  887.             p = s.peek();
  888.             // pecatenje (obrabotka) na jazelot na vrvot od magacinot
  889.             System.out.print(p.info.toString() + " ");
  890.             // brisenje na obraboteniot jazel od magacinot
  891.             s.pop();
  892.             // pridvizuvanje vo desno od obraboteniot jazel i povtoruvanje na
  893.             // postapkata za desnoto potsteblo na jazelot
  894.             p = p.right;
  895.  
  896.         }
  897.         System.out.println();
  898.  
  899.     }
  900.  
  901.     int insideNodesR(BNode<E> node) {
  902.         if (node == null)
  903.             return 0;
  904.  
  905.         if ((node.left == null) && (node.right == null))
  906.             return 0;
  907.  
  908.         return insideNodesR(node.left) + insideNodesR(node.right) + 1;
  909.     }
  910.  
  911.     public int insideNodes() {
  912.         return insideNodesR(root);
  913.     }
  914.  
  915.     int leavesR(BNode<E> node) {
  916.         if (node != null) {
  917.             if ((node.left == null) && (node.right == null))
  918.                 return 1;
  919.             else
  920.                 return (leavesR(node.left) + leavesR(node.right));
  921.         } else {
  922.             return 0;
  923.         }
  924.     }
  925.  
  926.     public int leaves() {
  927.         return leavesR(root);
  928.     }
  929.  
  930.     int depthR(BNode<E> node) {
  931.         if (node == null)
  932.             return 0;
  933.         if ((node.left == null) && (node.right == null))
  934.             return 0;
  935.         return (1 + Math.max(depthR(node.left), depthR(node.right)));
  936.     }
  937.  
  938.     public int depth() {
  939.         return depthR(root);
  940.     }
  941.  
  942.     void mirrorR(BNode<E> node) {
  943.         BNode<E> tmp;
  944.  
  945.         if (node == null)
  946.             return;
  947.  
  948.         // simetricno preslikuvanje na levoto i desnoto potsteblo
  949.         mirrorR(node.left);
  950.         mirrorR(node.right);
  951.  
  952.         // smena na ulogite na pokazuvacite na momentalniot jazel
  953.         tmp = node.left;
  954.         node.left = node.right;
  955.         node.right = tmp;
  956.  
  957.     }
  958.  
  959.     public void mirror() {
  960.         mirrorR(root);
  961.     }
  962.  
  963. }
  964.  
  965. class BNode<E> {
  966.  
  967.     public E info;
  968.     public BNode<E> left;
  969.     public BNode<E> right;
  970.  
  971.     static int LEFT = 1;
  972.     static int RIGHT = 2;
  973.  
  974.     public BNode(E info) {
  975.         this.info = info;
  976.         left = null;
  977.         right = null;
  978.     }
  979.  
  980.     public BNode(E info, BNode<E> left, BNode<E> right) {
  981.         this.info = info;
  982.         this.left = left;
  983.         this.right = right;
  984.     }
  985.  
  986.     @Override
  987.     public String toString() {
  988.         return "BNode{" +
  989.                 "info=" + info +
  990.                 '}';
  991.     }
  992. }
  993.  
  994. class BinarySearchTree<E extends Comparable<E>> {
  995.  
  996.     /**
  997.      * The tree root.
  998.      */
  999.     private BNode<E> root;
  1000.  
  1001.     /**
  1002.      * Construct the tree.
  1003.      */
  1004.     public BinarySearchTree() {
  1005.         root = null;
  1006.     }
  1007.  
  1008.     /**
  1009.      * Insert into the tree; duplicates are ignored.
  1010.      *
  1011.      * @param x the item to insert.
  1012.      */
  1013.     public void insert(E x) {
  1014.         root = insert(x, root);
  1015.     }
  1016.  
  1017.     /**
  1018.      * Remove from the tree. Nothing is done if x is not found.
  1019.      *
  1020.      * @param x the item to remove.
  1021.      */
  1022.     public void remove(E x) {
  1023.         root = remove(x, root);
  1024.     }
  1025.  
  1026.     /**
  1027.      * Find the smallest item in the tree.
  1028.      *
  1029.      * @return smallest item or null if empty.
  1030.      */
  1031.     public E findMin() {
  1032.         return elementAt(findMin(root));
  1033.     }
  1034.  
  1035.     /**
  1036.      * Find the largest item in the tree.
  1037.      *
  1038.      * @return the largest item of null if empty.
  1039.      */
  1040.     public E findMax() {
  1041.         return elementAt(findMax(root));
  1042.     }
  1043.  
  1044.     /**
  1045.      * Find an item in the tree.
  1046.      *
  1047.      * @param x the item to search for.
  1048.      * @return the matching item or null if not found.
  1049.      */
  1050.     public BNode<E> find(E x) {
  1051.         return find(x, root);
  1052.     }
  1053.  
  1054.     /**
  1055.      * Make the tree logically empty.
  1056.      */
  1057.     public void makeEmpty() {
  1058.         root = null;
  1059.     }
  1060.  
  1061.     /**
  1062.      * Test if the tree is logically empty.
  1063.      *
  1064.      * @return true if empty, false otherwise.
  1065.      */
  1066.     public boolean isEmpty() {
  1067.         return root == null;
  1068.     }
  1069.  
  1070.     /**
  1071.      * Print the tree contents in sorted order.
  1072.      */
  1073.     public void printTree() {
  1074.         if (isEmpty()) {
  1075.             System.out.println("Empty tree");
  1076.         } else {
  1077.             printTree(root);
  1078.         }
  1079.     }
  1080.  
  1081.     /**
  1082.      * Internal method to get element field.
  1083.      *
  1084.      * @param t the node.
  1085.      * @return the element field or null if t is null.
  1086.      */
  1087.     private E elementAt(BNode<E> t) {
  1088.         if (t == null)
  1089.             return null;
  1090.         return t.info;
  1091.     }
  1092.  
  1093.     /**
  1094.      * Internal method to insert into a subtree.
  1095.      *
  1096.      * @param x the item to insert.
  1097.      * @param t the node that roots the tree.
  1098.      * @return the new root.
  1099.      */
  1100.     private BNode<E> insert(E x, BNode<E> t) {
  1101.         if (t == null) {
  1102.             t = new BNode<E>(x, null, null);
  1103.         } else if (x.compareTo(t.info) < 0) {
  1104.             t.left = insert(x, t.left);
  1105.         } else if (x.compareTo(t.info) > 0) {
  1106.             t.right = insert(x, t.right);
  1107.         } else ;  // Duplicate; do nothing
  1108.         return t;
  1109.     }
  1110.  
  1111.     /**
  1112.      * Internal method to remove from a subtree.
  1113.      *
  1114.      * @param x the item to remove.
  1115.      * @param t the node that roots the tree.
  1116.      * @return the new root.
  1117.      *
  1118.      * Time Complexity O(height) = O(logn)
  1119.      */
  1120.  
  1121.     /**
  1122.      * Because in the worst case this algorithm must search from the root of the tree to the leaf farthest from the root,
  1123.      * the search operation takes time proportional to the tree's height. On average,
  1124.      * binary search trees with n nodes have O(log n) height. However, in the worst case,
  1125.      * binary search trees can have O(n) height, when the unbalanced tree resembles a linked list (degenerate tree).
  1126.      */
  1127.     private BNode<E> remove(Comparable x, BNode<E> t) {
  1128.         if (t == null)
  1129.             return t;   // Item not found; do nothing
  1130.  
  1131.         if (x.compareTo(t.info) < 0) {
  1132.             t.left = remove(x, t.left);
  1133.         } else if (x.compareTo(t.info) > 0) {
  1134.             t.right = remove(x, t.right);
  1135.         } else if (t.left != null && t.right != null) { // Two children
  1136.             t.info = findMin(t.right).info;
  1137.             t.right = remove(t.info, t.right);
  1138.         } else {
  1139.             if (t.left != null)
  1140.                 return t.left;
  1141.             else
  1142.                 return t.right;
  1143.         }
  1144.         return t;
  1145.     }
  1146.  
  1147.     /**
  1148.      * Internal method to find the smallest item in a subtree.
  1149.      *
  1150.      * @param t the node that roots the tree.
  1151.      * @return node containing the smallest item.
  1152.      */
  1153.     private BNode<E> findMin(BNode<E> t) {
  1154.         if (t == null) {
  1155.             return null;
  1156.         } else if (t.left == null) {
  1157.             return t;
  1158.         }
  1159.         return findMin(t.left);
  1160.     }
  1161.  
  1162.     /**
  1163.      * Internal method to find the largest item in a subtree.
  1164.      *
  1165.      * @param t the node that roots the tree.
  1166.      * @return node containing the largest item.
  1167.      */
  1168.     private BNode<E> findMax(BNode<E> t) {
  1169.         if (t == null) {
  1170.             return null;
  1171.         } else if (t.right == null) {
  1172.             return t;
  1173.         }
  1174.         return findMax(t.right);
  1175.     }
  1176.  
  1177.     /**
  1178.      * Internal method to find an item in a subtree.
  1179.      *
  1180.      * @param x is item to search for.
  1181.      * @param t the node that roots the tree.
  1182.      * @return node containing the matched item.
  1183.      */
  1184.     private BNode<E> find(E x, BNode<E> t) {
  1185.         if (t == null)
  1186.             return null;
  1187.  
  1188.         if (x.compareTo(t.info) < 0) {
  1189.             return find(x, t.left);
  1190.         } else if (x.compareTo(t.info) > 0) {
  1191.             return find(x, t.right);
  1192.         } else {
  1193.             return t;    // Match
  1194.         }
  1195.     }
  1196.  
  1197.     /**
  1198.      * Internal method to print a subtree in sorted order.
  1199.      *
  1200.      * @param t the node that roots the tree.
  1201.      */
  1202.     private void printTree(BNode<E> t) {
  1203.         if (t != null) {
  1204.             printTree(t.left);
  1205.             System.out.println(t.info);
  1206.             printTree(t.right);
  1207.         }
  1208.     }
  1209.  
  1210.     // Test program
  1211.     public static void main(String[] args) {
  1212.         Random r = new Random(System.currentTimeMillis());
  1213.         BinarySearchTree<Integer> bst = new BinarySearchTree<>();
  1214.  
  1215.         for (int i = 0; i < 10; i++) {
  1216.             bst.insert(Math.abs(i - 10));
  1217.         }
  1218.  
  1219.  
  1220.         bst.printTree();
  1221.  
  1222.         bst.remove(4);
  1223.         bst.printTree();
  1224.  
  1225.     }
  1226. }
Advertisement
Add Comment
Please, Sign In to add comment