Changed find(int key) method to return null when node is not found, and updated docs accordingly. Issue #104.

This commit is contained in:
mpokryva 2017-09-29 11:21:47 -04:00
parent 0aee19d427
commit e5381585a5

View File

@ -1,20 +1,20 @@
/** /**
* This entire class is used to build a Binary Tree data structure. * This entire class is used to build a Binary Tree data structure.
* There is the Node Class and the Tree Class, both explained below. * There is the Node Class and the Tree Class, both explained below.
* *
* @author Unknown * @author Unknown
* *
*/ */
/** /**
* This class implements the nodes that will go on the Binary Tree. * This class implements the nodes that will go on the Binary Tree.
* They consist of the data in them, the node to the left, the node * They consist of the data in them, the node to the left, the node
* to the right, and the parent from which they came from. * to the right, and the parent from which they came from.
* *
* @author Unknown * @author Unknown
* *
*/ */
class Node{ class Node{
/** Data for the node */ /** Data for the node */
public int data; public int data;
@ -40,14 +40,14 @@ class Node{
/** /**
* A binary tree is a data structure in which an element * A binary tree is a data structure in which an element
* has two successors(children). The left child is usually * has two successors(children). The left child is usually
* smaller than the parent, and the right child is usually * smaller than the parent, and the right child is usually
* bigger. * bigger.
* *
* @author Unknown * @author Unknown
* *
*/ */
class Tree{ class Tree{
/** The root of the Binary Tree */ /** The root of the Binary Tree */
private Node root; private Node root;
@ -65,20 +65,18 @@ class Tree{
* @param key Value being looked for * @param key Value being looked for
* @return The node if it finds it, otherwise returns the parent * @return The node if it finds it, otherwise returns the parent
*/ */
public Node find(int key){ public Node find(int key) {
Node current = root; Node current = root;
Node last = root; while (current != null) {
while(current != null){ if(key < current.data) {
last = current;
if(key < current.data)
current = current.left; current = current.left;
else if(key > current.data) } else if(key > current.data) {
current = current.right; current = current.right;
//If you find the value return it } else { // If you find the value return it
else
return current; return current;
} }
return last; }
return null;
} }
/** /**
@ -267,4 +265,4 @@ class Tree{
System.out.print(localRoot.data + " "); System.out.print(localRoot.data + " ");
} }
} }
} }