Last active
August 29, 2015 14:13
-
-
Save dmnugent80/f3e921ef2903988fa5b9 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
| public class TreeNode{ | |
| public int data; | |
| public TreeNode left; | |
| public TreeNode right; | |
| public TreeNode(int d){ | |
| this.data = d; | |
| this.left = null; | |
| this.right = null; | |
| } | |
| } | |
| public class BinarySearchTree{ | |
| public root; | |
| public BinarySearchTree(){ | |
| root = null; | |
| } | |
| public boolean addNode(int d){ | |
| if (root == null){ | |
| root = new TreeNode(d); | |
| return true; | |
| } | |
| else if (root.data == d){ | |
| return false; | |
| } | |
| else{ | |
| return addNodeHelper(root, d); | |
| } | |
| } | |
| private boolean addNodeHelper(TreeNode node, int d){ | |
| if (d == node.data){ | |
| return false; | |
| } | |
| else if (d < node.data){ | |
| if (node.left == null){ | |
| node.left = new TreeNode(d); | |
| return true; | |
| } | |
| else{ | |
| return addNodeHelper(node.left, d); | |
| } | |
| else{ | |
| if (node.right == null){ | |
| node.right = new TreeNode(d); | |
| return true; | |
| } | |
| else{ | |
| return addNodeHelper(node.right, d); | |
| } | |
| } | |
| } | |
| } | |
| public TreeNode find(int d){ | |
| TreeNode curr = root; | |
| while (curr != null){ | |
| if (curr.data == d){ | |
| return curr; | |
| } | |
| else if (d < curr.data){ | |
| curr = curr.left; | |
| } | |
| else{ | |
| curr = curr.right; | |
| } | |
| } | |
| return null; | |
| } | |
| public TreeNode findLargest(TreeNode node){ | |
| TreeNode curr = node; | |
| if (curr == null){ | |
| return null; | |
| } | |
| while (curr.right != null){ | |
| curr = curr.right; | |
| } | |
| return curr; | |
| } | |
| public TreeNode findSecondLargest(TreeNode node){ | |
| TreeNode curr = node; | |
| while (curr != null){ | |
| if (curr.right == null && curr.left != null){ | |
| //largest is largest of left sub-tree | |
| return findLargest(curr.left); | |
| } | |
| else if (curr.right != null && curr.right.right == null && curr.right.left == null){ | |
| //curr is second largest, return it | |
| return curr; | |
| } | |
| curr = curr.right; | |
| } | |
| return null; | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment