hqt

BST Short version

hqt
Jul 18th, 2013
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.89 KB | None | 0 0
  1. import java.util.*;
  2. public class BinarySearchTree {
  3.     public static class Node {
  4.         int value;
  5.         Node left, right;
  6.         public Node(int value) { this.value = value;}
  7.     }
  8.     Node root = null;
  9.     public void insert(int value) {
  10.         root = insert(root, value);
  11.     }
  12.     private Node insert(Node root, int value) {
  13.         if (root == null) return new Node(value);
  14.         if (value <= root.value) root.left = insert(root.left, value);
  15.         else root.right = insert(root.right, value);
  16.         return root;
  17.     }
  18.     private void FindDistance(Node root, int small, int big) {
  19.         if (root == null) return;
  20.         List<Node> p1 = new ArrayList<Node>();
  21.         List<Node> p2 = new ArrayList<Node>();
  22.         boolean res1 = true, res2 = true;
  23.         if (big == root.value) {
  24.             res1 &= FindPath(root.left, small, p1);
  25.             p2.add(root);
  26.         }
  27.         else if (small == root.value) {
  28.             p1.add(root);
  29.             res2 &= FindPath(root.right, big, p2);
  30.         }
  31.         else if (big < root.value) FindDistance(root.left, small, big);
  32.         else if (small > root.value) FindDistance(root.right, small, big);
  33.         else if (small < root.value && big > root.value) {
  34.             p1.add(root);
  35.             res1 &= FindPath(root.left, small, p1);
  36.             res2 &= FindPath(root.right, big, p2);
  37.         }
  38.         if (!res1 || !res2) {
  39.             System.out.println("does not contain this node in binary search tree");
  40.             return;
  41.         }
  42.         for (int i = p1.size() - 1; i >= 0; i--) System.out.print(p1.get(i).value + "->");
  43.         for (int i = 0;i < p2.size() - 1; i++) System.out.print(p2.get(i).value + "->");
  44.         System.out.println(p2.get(p2.size() - 1).value);
  45.     }
  46.     private boolean FindPath(Node root, int val, List<Node> path) {
  47.         if (root == null) return false;
  48.         path.add(root);
  49.         if (root.value == val) return true;
  50.         if (root.value > val) return FindPath(root.left, val, path);
  51.         else return FindPath(root.right, val, path);
  52.     }
  53.     public void FindDistance(int a, int b) {
  54.         if (a > b) FindDistance(root, b, a);
  55.         else FindDistance(root, b, a);
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment