주어진 트리가 BST인지 찾기위한 코드를 작성했습니다. 하지만 리팩토링에 도움이 필요합니다. 내가 찾고있는 것들 중 일부는 다음과 같습니다 리 팩터링 코드 이진 트리가 BST인지 찾기
을
- 는 임시 변수의 없애 버리는, 나는 사람들이 가지고있는 다른 모든 리팩터링 아이디어에 감사 할 것입니다.
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; } }
왜 주문 순회를하지 않습니까? 단순히 이전에 보았던 가치를 추적하십시오. – phant0m
더 잘 맞는 [CodeReview.SE] (http://codereview.stackexchange.com/) IMHO – amit
이 숙제가 있습니까? – theJollySin