저는 일부 데이터 구조에 대해 자세히 배우려고 노력했으며 제대로 작동하려면 이진 스플레이 트리를 얻으려고합니다. 다음 코드를 실행할 때마다 내가 찾고있는 노드가 과거의 루트보다 두 개 이상 많다는 것을 알려주고 루트에서 전체면을 삭제합니다. 노드가 맨 위에서 한 레벨 아래에 있으면 잘 작동합니다.스플레이 트리 검색 구현
나는 무엇이 잘못 될지 모르지만 내 회전 기능과 관련이 있다고 가정합니다. 나는 이것을 내가 모델링 한 인서트 함수에 대해 제대로 작동하도록했다.
public class SplayBST {
Node root;
int count;
int level = 0;
boolean found = false;
public SplayBST() {
root = null;
count = 0;
}
public String searchIt(String x) {
//after finishing search method I need to check if splaySearch exists then don't insert just splay it
splaySearch(root, x);
if (this.found == true) {
this.found = false;
return x;
}
else {
return null;
}
}
Node splaySearch(Node h, String x) {
if (h == null) {
return null;
}
if (x.compareTo(h.value) < 0) {
try {
if (x.compareTo(h.left.value) < 0) {
h.left.left = splaySearch(h.left.left, x);
h = rotateRight(h);
} else if (x.compareTo(h.left.value) > 0) {
h.left.right = splaySearch(h.left.right, x);
h.left = rotateLeft(h.left);
}
else {
this.found = true;
return h.left;
}
return rotateRight(h);
}
catch (NullPointerException ex) {
return null;
}
}
else { //basically x.compareTo(h.value)>0
try {
if (x.compareTo(h.right.value) > 0) {
h.right.right = splaySearch(h.right.right, x);
h = rotateLeft(h);
} else if (x.compareTo(h.right.value) < 0) {
h.right.left = splaySearch(h.right.left, x);
h.right = rotateRight(h.right);
}
else {
this.found = true;
return h.right;
}
return rotateLeft(h);
}
catch (NullPointerException ex) {
return null;
}
}
}
Node rotateLeft(Node h) {
Node x = h.right;
h.right = x.left;
x.left = h;
return x;
}
Node rotateRight(Node h) {
Node x = h.left;
h.left = x.right;
x.right = h;
return x;
}
class Node {
Node left;
Node right;
String value;
int pos;
public Node(String x) {
left = null;
right = null;
value = x;
}
}
}
도움을 주셔서 감사합니다. – clifgray
제 접근 방식을 사용해 주셔서 감사합니다. 그걸 작동 시켰 니? –
하하 나는 아직도 그것에 대해 연구 중이다. 잠시 시간이 걸릴 것이라고 상상할 것이다. – clifgray