JavaAlgorithms
Elementary and no so elementary Java algorithms
treeAlgorithms/TreeBuilder.java
Go to the documentation of this file.
00001 
00009 package treeAlgorithms;
00010 
00022 public class TreeBuilder<T extends Comparable<T>> {
00023     private TreeNode<T> mRoot = null;
00024 
00028     public TreeBuilder() {
00029     }
00030 
00038     public TreeBuilder(TreeNode<T> root) {
00039         this.mRoot = root;
00040     }
00041 
00042     public TreeBuilder(T[] vals) {
00043         if (vals != null) {
00044             for (T val : vals) {
00045                 this.addNode(val);
00046             }
00047         }
00048     }
00049 
00059     protected boolean addNode(TreeNode<T> root, T newVal) {
00060         Comparable<T> rootVal = root.getValue();
00061         boolean found = true;
00062         if (rootVal.compareTo(newVal) == 0) {
00063             found = true;
00064         } else if (rootVal.compareTo(newVal) < 0) {
00065             if (root.getRight() != null) {
00066                 addNode(root.getRight(), newVal);
00067             } else {
00068                 TreeNode<T> newNode = new TreeNode<T>(newVal);
00069                 root.setRight(newNode);
00070             }
00071         } else if (rootVal.compareTo(newVal) > 0) {
00072             if (root.getLeft() != null) {
00073                 addNode(root.getLeft(), newVal);
00074             } else {
00075                 TreeNode<T> newNode = new TreeNode<T>(newVal);
00076                 root.setLeft(newNode);
00077             }
00078         }
00079         return found;
00080     }
00081 
00088     public boolean addNode(T newVal) {
00089         boolean found = false;
00090         if (newVal != null) {
00091             if (mRoot == null) {
00092                 TreeNode<T> newNode = new TreeNode<T>(newVal);
00093                 mRoot = newNode;
00094             } else {
00095                 found = addNode(mRoot, newVal);
00096             }
00097         }
00098         return found;
00099     }
00100 
00104     public TreeNode<T> getTree() {
00105         return mRoot;
00106     }
00107 }
 All Classes Namespaces Files Functions Variables