Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class BNS {
- private BN root = null;
- public boolean insert(int element) {
- BN toInsert = new BN(element);
- BN child = root;
- BN parent = null;
- if(child == null) {
- child = toInsert;
- }
- while(child != null) {
- parent = child;
- if(parent.element > element) {
- child = child.left;
- }
- else if (parent.element < element) {
- child = child.right;
- }
- }
- if(parent.element > element) {
- parent.left = toInsert;
- return true;
- }
- else if(parent.element < element) {
- parent.right = toInsert;
- return true;
- }
- return false;
- }
- public void printPath(int element) {
- String path = "";
- BN current = root;
- if(current.element == element) {
- System.out.println(path += "root");
- return;
- }
- else {
- while(current != null) {
- if(current.element == element) {
- System.out.println(path);
- return;
- }
- if(current.element > element) {
- current = current.left;
- path += "l";
- }
- else if(current.element < element) {
- current = current.right;
- path += "r";
- }
- }
- }
- System.out.println(path);
- }
- }
- public class BN {
- public int element;
- public BN left, right;
- public BN(int element) {
- this.element = element;
- this.left = null;
- this.right = null;
- }
- public BN(int element, BN left, BN right) {
- this.element = element;
- this.left = left;
- this.right = right;
- }
- }
- public class BNSTest {
- public static void main(String[] args) {
- BNS tree = new BNS();
- tree.insert(10);
- tree.insert(52);
- tree.insert(89);
- tree.insert(4);
- tree.insert(35);
- tree.insert(20);
- tree.insert(85);
- tree.insert(12);
- tree.insert(1);
- tree.insert(8);
- tree.insert(7);
- tree.insert(2);
- tree.insert(3);
- tree.printPath(12);
- System.out.println("Hallo");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement