BST(Java-Binary Search Tree) 알고리즘 샘플 코드 공유
이진 검색 트리는 연결 목록 삽입의 유연성과 순서 있는 배열 검색의 효율성을 결합한 알고리즘입니다. 다음은 BST의 다양한 메소드를 구현하기 위한 순수 코드이다.
이진 검색 트리(BST) 정의
이진 정렬 트리는 빈 트리이거나 다음 속성을 가진 이진 트리 :
- 의 값
왼쪽 하위 트리가 비어 있지 않으면 왼쪽 하위 트리 은 루트 노드
- 보다 작거나 같습니다. 오른쪽 하위 트리가 비어 있지 않으면
크거나오른쪽 하위 트리 모든 노드의 값은 해당 루트 노드
값보다- 같습니다. 왼쪽 및 오른쪽 하위 트리도 이진 정렬 트리의 기본 노드에 대해
를 구현합니다.public class BST<K extends Comparable<K>, V> { private Node root; private class Node { private K key; private V value; private Node left; private Node right; private int N; public Node(K key, V value, int N) { this.key = key; this.value = value; this.N = N; } } public int size() { return size(root); } private int size(Node x) { if (x == null) return 0; else return x.N; } }로그인 후 복사
각각 - getpublic V get(K key) {
return get(root, key);
}
private V get(Node root, K key) {
if (root == null)
return null;
int comp = key.compareTo(root.key);
if (comp == 0)
return root.value;
else if (comp < 0)
return get(root.left, key);
else
return get(root.right, key);
}
로그인 후 복사
public V get(K key) { return get(root, key); } private V get(Node root, K key) { if (root == null) return null; int comp = key.compareTo(root.key); if (comp == 0) return root.value; else if (comp < 0) return get(root.left, key); else return get(root.right, key); }
값 수정/새 값 삽입——put public void put(K key, V value) {
root = put(root, key, value);
}
private Node put(Node root, K key, V value) {
if (root == null)
return new Node(key, value, 1);
int comp = key.compareTo(root.key);
if (comp == 0)
root.value = value;
else if (comp < 0)
root.left = put(root.left, key, value);
else
root.right = put(root.right, key, value);
root.N = size(root.left) + size(root.right) + 1;
return root;
}
로그인 후 복사
public void put(K key, V value) { root = put(root, key, value); } private Node put(Node root, K key, V value) { if (root == null) return new Node(key, value, 1); int comp = key.compareTo(root.key); if (comp == 0) root.value = value; else if (comp < 0) root.left = put(root.left, key, value); else root.right = put(root.right, key, value); root.N = size(root.left) + size(root.right) + 1; return root; }
최대값/최소값——min /max public K min() {
return min(root).key;
}
private Node min(Node root) {
if (root.left == null)
return root;
return min(root.left);
}
로그인 후 복사 public K max() {
return max(root).key;
}
private Node max(Node root2) {
if (root.right == null)
return root;
return max(root.right);
}
로그인 후 복사
public K min() { return min(root).key; } private Node min(Node root) { if (root.left == null) return root; return min(root.left); }
public K max() { return max(root).key; } private Node max(Node root2) { if (root.right == null) return root; return max(root.right); }
올림/내림——바닥/천장 public K floor(K key) {
Node x = floor(root, key);
if (x == null)
return null;
return x.key;
}
private Node floor(Node root, K key) {
if (root == null)
return null;
int comp = key.compareTo(root.key);
if (comp < 0)
return floor(root.left, key);
else if (comp > 0 && root.right != null
&& key.compareTo(min(root.right).key) >= 0)
return floor(root.right, key);
else
return root;
}
로그인 후 복사 public K ceiling(K key) {
Node x = ceiling(root, key);
if (x == null)
return null;
return x.key;
}
private Node ceiling(Node root, K key) {
if (root == null)
return null;
int comp = key.compareTo(root.key);
if (comp > 0)
return ceiling(root.right, key);
else if (comp < 0 && root.left != null
&& key.compareTo(max(root.left).key) >= 0)
return ceiling(root.left, key);
else
return root;
}
로그인 후 복사
public K floor(K key) { Node x = floor(root, key); if (x == null) return null; return x.key; } private Node floor(Node root, K key) { if (root == null) return null; int comp = key.compareTo(root.key); if (comp < 0) return floor(root.left, key); else if (comp > 0 && root.right != null && key.compareTo(min(root.right).key) >= 0) return floor(root.right, key); else return root; }
public K ceiling(K key) { Node x = ceiling(root, key); if (x == null) return null; return x.key; } private Node ceiling(Node root, K key) { if (root == null) return null; int comp = key.compareTo(root.key); if (comp > 0) return ceiling(root.right, key); else if (comp < 0 && root.left != null && key.compareTo(max(root.left).key) >= 0) return ceiling(root.left, key); else return root; }
선택——select public K select(int k) {
//找出BST中序号为k的键
return select(root, k);
}
private K select(Node root, int k) {
if (root == null)
return null;
int comp = k - size(root.left);
if (comp < 0)
return select(root.left, k);
else if (comp > 0)
return select(root.right, k - (size(root.left) + 1));
else
return root.key;
}
로그인 후 복사
public K select(int k) { //找出BST中序号为k的键 return select(root, k); } private K select(Node root, int k) { if (root == null) return null; int comp = k - size(root.left); if (comp < 0) return select(root.left, k); else if (comp > 0) return select(root.right, k - (size(root.left) + 1)); else return root.key; }
순위 - 순위 public int rank(K key) {
//找出BST中键为key的序号是多少
return rank(root, key);
}
private int rank(Node root, K key) {
if (root == null)
return 0;
int comp = key.compareTo(root.key);
if (comp == 0)
return size(root.left);
else if (comp < 0)
return rank(root.left, key);
else
return 1 + size(root.left) + rank(root.right, key);
}
로그인 후 복사
public int rank(K key) { //找出BST中键为key的序号是多少 return rank(root, key); } private int rank(Node root, K key) { if (root == null) return 0; int comp = key.compareTo(root.key); if (comp == 0) return size(root.left); else if (comp < 0) return rank(root.left, key); else return 1 + size(root.left) + rank(root.right, key); }
최소/최대 키 삭제 - deleteMin/deleteMax public void deleteMin() {
root = deleteMin(root);
}
private Node deleteMin(Node root) {
if (root.left == null)
return root.right;
root.left = deleteMin(root.left);
root.N = size(root.left) + size(root.right) + 1;
return root;
}
로그인 후 복사rrree
public void deleteMin() { root = deleteMin(root); } private Node deleteMin(Node root) { if (root.left == null) return root.right; root.left = deleteMin(root.left); root.N = size(root.left) + size(root.right) + 1; return root; }
키 삭제 - 삭제 public void deleteMax() {
root = deleteMax(root);
}
private Node deleteMax(Node root) {
if (root.right == null)
return root.left;
root.right = deleteMax(root.right);
root.N = size(root.left) + size(root.right) + 1;
return root;
}
로그인 후 복사
public void deleteMax() { root = deleteMax(root); } private Node deleteMax(Node root) { if (root.right == null) return root.left; root.right = deleteMax(root.right); root.N = size(root.left) + size(root.right) + 1; return root; }
순차 인쇄 트리——인쇄 public void delete(K key) {
root = delete(root, key);
}
private Node delete(Node root, K key) {
if (root == null)
return null;
int comp = key.compareTo(root.key);
if (comp == 0) {
if (root.right == null)
return root = root.left;
if (root.left == null)
return root = root.right;
Node t = root;
root = min(t.right);
root.left = t.left;
root.right = deleteMin(t.right);
} else if (comp < 0)
root.left = delete(root.left, key);
else
root.right = delete(root.right, key);
root.N = size(root.left) + size(root.right) + 1;
return root;
}
로그인 후 복사
public void delete(K key) { root = delete(root, key); } private Node delete(Node root, K key) { if (root == null) return null; int comp = key.compareTo(root.key); if (comp == 0) { if (root.right == null) return root = root.left; if (root.left == null) return root = root.right; Node t = root; root = min(t.right); root.left = t.left; root.right = deleteMin(t.right); } else if (comp < 0) root.left = delete(root.left, key); else root.right = delete(root.right, key); root.N = size(root.left) + size(root.right) + 1; return root; }
위 내용은 BST(Java-Binary Search Tree) 알고리즘 샘플 코드 공유의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Java의 Weka 가이드. 여기에서는 소개, weka java 사용 방법, 플랫폼 유형 및 장점을 예제와 함께 설명합니다.

Java의 Smith Number 가이드. 여기서는 정의, Java에서 스미스 번호를 확인하는 방법에 대해 논의합니다. 코드 구현의 예.

이 기사에서는 가장 많이 묻는 Java Spring 면접 질문과 자세한 답변을 보관했습니다. 그래야 면접에 합격할 수 있습니다.

Java 8은 스트림 API를 소개하여 데이터 컬렉션을 처리하는 강력하고 표현적인 방법을 제공합니다. 그러나 스트림을 사용할 때 일반적인 질문은 다음과 같은 것입니다. 기존 루프는 조기 중단 또는 반환을 허용하지만 스트림의 Foreach 메소드는이 방법을 직접 지원하지 않습니다. 이 기사는 이유를 설명하고 스트림 처리 시스템에서 조기 종료를 구현하기위한 대체 방법을 탐색합니다. 추가 읽기 : Java Stream API 개선 스트림 foreach를 이해하십시오 Foreach 메소드는 스트림의 각 요소에서 하나의 작업을 수행하는 터미널 작동입니다. 디자인 의도입니다

Java의 TimeStamp to Date 안내. 여기서는 소개와 예제와 함께 Java에서 타임스탬프를 날짜로 변환하는 방법에 대해서도 설명합니다.

캡슐은 3 차원 기하학적 그림이며, 양쪽 끝에 실린더와 반구로 구성됩니다. 캡슐의 부피는 실린더의 부피와 양쪽 끝에 반구의 부피를 첨가하여 계산할 수 있습니다. 이 튜토리얼은 다른 방법을 사용하여 Java에서 주어진 캡슐의 부피를 계산하는 방법에 대해 논의합니다. 캡슐 볼륨 공식 캡슐 볼륨에 대한 공식은 다음과 같습니다. 캡슐 부피 = 원통형 볼륨 2 반구 볼륨 안에, R : 반구의 반경. H : 실린더의 높이 (반구 제외). 예 1 입력하다 반경 = 5 단위 높이 = 10 단위 산출 볼륨 = 1570.8 입방 단위 설명하다 공식을 사용하여 볼륨 계산 : 부피 = π × r2 × h (4

Java는 초보자와 숙련된 개발자 모두가 배울 수 있는 인기 있는 프로그래밍 언어입니다. 이 튜토리얼은 기본 개념부터 시작하여 고급 주제를 통해 진행됩니다. Java Development Kit를 설치한 후 간단한 "Hello, World!" 프로그램을 작성하여 프로그래밍을 연습할 수 있습니다. 코드를 이해한 후 명령 프롬프트를 사용하여 프로그램을 컴파일하고 실행하면 "Hello, World!"가 콘솔에 출력됩니다. Java를 배우면 프로그래밍 여정이 시작되고, 숙달이 깊어짐에 따라 더 복잡한 애플리케이션을 만들 수 있습니다.
