I have written an code to find if a given tree is a BST. Need help in refactoring it. Some of the things I am looking are.
- Getting Rid of temp variables (As suggested by Martin Fowler)
- Combining leftTreeMax and RighTreeMin methods
- Better naming of methods.
Also it will be great if someone can suggest other refactorings which i can do.
package com.cc.bst;
import com.cc.queue.Queue;
import com.cc.trees.BinaryTreeNode;
public class IsBinaryTreeBST {
public static boolean binaryTreeBST ( BinaryTreeNode root) {
if (root == null) {
return false;
}
int maxVal = leftTreeMax(root.getLeft());
int minVal = rightTreeMin(root.getRight());
int rootVal = root.getData();
if (maxVal == 0 || minVal == 0 ) {
return false;
}
if (rootVal > maxVal && rootVal < minVal) {
return true;
}
return false;
}
private static int leftTreeMax (BinaryTreeNode node) {
if (node == null) {
return 0;
}
Queue nodeQueue = new Queue();
nodeQueue.enqueue(node);
int maxValue = node.getData();
while (!nodeQueue.isEmpty()) {
BinaryTreeNode tempNode = (BinaryTreeNode) nodeQueue.dequeue();
BinaryTreeNode left = tempNode.getLeft();
BinaryTreeNode right = tempNode.getRight();
if (left != null ) {
if (left.getData() > tempNode.getData()) {
return 0;
}
nodeQueue.enqueue(left);
}
if (right != null) {
if ( tempNode.getData() > right.getData()) {
return 0;
}
nodeQueue.enqueue(right);
}
if (tempNode.getData() > maxValue) {
maxValue = tempNode.getData();
}
}
System.out.println("---------- maxVal -------->" + maxValue);
return maxValue;
}
private static int rightTreeMin(BinaryTreeNode node) {
if (node == null) {
return 0;
}
Queue nodeQueue = new Queue();
nodeQueue.enqueue(node);
int minValue = node.getData();
while (!nodeQueue.isEmpty()) {
BinaryTreeNode tempNode = (BinaryTreeNode) nodeQueue.dequeue();
BinaryTreeNode left = tempNode.getLeft();
BinaryTreeNode right = tempNode.getRight();
System.out.println("---------- tempNode -------->" + tempNode.getData());
if (left != null ) {
System.out.println("---------- left -------->" + left.getData());
if (left.getData() > tempNode.getData()) {
return 0;
}
nodeQueue.enqueue(left);
}
if (right != null) {
if ( tempNode.getData() > right.getData()) {
return 0;
}
System.out.println("---------- right -------->" + right.getData());
nodeQueue.enqueue(right);
}
if (tempNode.getData() < minValue) {
minValue = tempNode.getData();
}
}
System.out.println("---------- minVal -------->" + minValue);
return minValue;
}
}