我已经编写了代码来查找给定的树是否是 BST。但我需要帮助重构它。我正在寻找的一些东西是:
- 摆脱临时变量(如 Martin Fowler 所建议)
- 结合 leftTreeMax 和 RightTreeMin 方法
- 更好的方法名称
另外,我会感谢人们提出的任何其他重构想法。
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;
}
}