Last active
December 10, 2019 07:24
-
-
Save t9toqwerty/7e9261555b49b46053cad574b226c454 to your computer and use it in GitHub Desktop.
Binary Search Tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package app; | |
public class BinarySearchTree { | |
BinaryTreeNode root; | |
public BinarySearchTree() { | |
this.root = null; | |
} | |
public void insert(int data) { | |
if (this.root == null) { | |
this.root = new BinaryTreeNode(data); | |
return; | |
} | |
BinaryTreeNode temp = root; | |
BinaryTreeNode parent = null; | |
while (temp != null) { | |
parent = temp; | |
if (data > temp.data) { | |
temp = temp.right; | |
} else if (data < temp.data) { | |
temp = temp.left; | |
} | |
} | |
if (parent.data > data) { | |
parent.left = new BinaryTreeNode(data); | |
} else if (parent.data < data) { | |
parent.right = new BinaryTreeNode(data); | |
} | |
} | |
/** | |
* TODO: Complete This Method | |
* | |
* @param root | |
* @param data | |
*/ | |
public BinaryTreeNode insertRecursively(BinaryTreeNode root, int data) { | |
if (root == null) { | |
root = new BinaryTreeNode(data); | |
return root; | |
} | |
if (root.data > data) { | |
this.insertRecursively(root.left, data); | |
} else { | |
this.insertRecursively(root.right, data); | |
} | |
return root; | |
} | |
public boolean searchData(BinaryTreeNode root, int data) { | |
BinaryTreeNode temp = root; | |
while (temp != null) { | |
if (temp.data == data) { | |
return true; | |
} | |
if (temp.data < data) { | |
temp = temp.right; | |
} else { | |
temp = temp.left; | |
} | |
} | |
return false; | |
} | |
public void inOrderTraversal(BinaryTreeNode root) { | |
if (root == null) { | |
return; | |
} | |
BinaryTreeNode temp = root; | |
this.inOrderTraversal(temp.left); | |
System.out.print(temp.data + " "); | |
this.inOrderTraversal(temp.right); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.company; | |
/** | |
* BinaryTreeNode | |
*/ | |
public class BinaryTreeNode { | |
int data; | |
BinaryTreeNode left; | |
BinaryTreeNode right; | |
BinaryTreeNode(int data) { | |
this.data = data; | |
this.left = null; | |
this.right = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment