JavaAlgorithms
Elementary and no so elementary Java algorithms
|
00001 00009 package treeAlgorithms; 00010 00016 public class Algorithms { 00017 00024 public interface NodeVisitor<T extends Comparable<T>> { 00030 void visit(TreeNode<T> node); 00031 } // interface NodeVistor 00032 00033 private Algorithms() { 00034 } 00035 00047 public static <T extends Comparable<T>> boolean isOrdered(TreeNode<T> root) { 00048 boolean ordered = false; 00049 if (root != null) { 00050 ordered = true; 00051 if (root.getLeft() != null) { 00052 boolean orderedBranch = isOrdered(root.getLeft()); 00053 if (!orderedBranch) { 00054 ordered = false; 00055 } 00056 } 00057 if (root.getRight() != null) { 00058 boolean orderedBranch = isOrdered(root.getRight()); 00059 if (!orderedBranch) { 00060 ordered = false; 00061 } 00062 } 00063 if (ordered) { 00064 Comparable<T> rootVal = root.getValue(); 00065 if (root.getLeft() != null) { 00066 @SuppressWarnings("unchecked") 00067 T leftVal = (T) root.getLeft().getValue(); 00068 if (rootVal.compareTo(leftVal) < 0) { 00069 ordered = false; 00070 } 00071 } 00072 if (root.getRight() != null) { 00073 @SuppressWarnings("unchecked") 00074 T rightVal = (T) root.getRight().getValue(); 00075 if (rootVal.compareTo(rightVal) > 0) { 00076 ordered = false; 00077 } 00078 } 00079 } 00080 } 00081 return ordered; 00082 } 00083 00097 public static <T extends Comparable<T>> void inOrder(TreeNode<T> root, NodeVisitor<T> visitor) { 00098 if (root != null) { 00099 inOrder(root.getLeft(), visitor); 00100 visitor.visit(root); 00101 inOrder(root.getRight(), visitor); 00102 } 00103 } // inOrder 00104 00105 }