티스토리 뷰
package byown.practice;
public class TreeNode {
char data;
TreeNode left;
TreeNode right;
public TreeNode() {
this.left = null;
this.right = null;
}
public TreeNode(char data) {
this.data = data;
this.left = null;
this.right = null;
}
public Object getData() {
return data;
}
}
package byown.practice;
public class BinarySearchTree {
private TreeNode root = new TreeNode();
public TreeNode insertKey(TreeNode root, char x) {
TreeNode p = root;
TreeNode newNode = new TreeNode(x);
if(p == null) {
return newNode;
} else if (p.data > newNode.data) {
p.left = insertKey(p.left, x);
return p;
} else if (p.data < newNode.data) {
p.right = insertKey(p.right, x);
return p;
} else {
return p;
}
}
public void insertBST(char x) {
root = insertKey(root, x);
}
public TreeNode searchBST(char x) {
TreeNode p = root;
while (p != null) {
if(x < p.data) {
p = p.left;
}
else if (x > p.data) {
p = p.right;
}
else return p;
}
return p;
}
public void inorder(TreeNode root) {
if (root != null) {
inorder(root.left);
System.out.println(root.data + " ");
inorder(root.right);
}
}
public void printBST() {
inorder(root);
System.out.println();
}
}
package byown.practice;
public class BstTest {
public static void main(String[] args) {
BinarySearchTree bst = new BinarySearchTree();
bst.insertBST('G');
bst.insertBST('I');
bst.insertBST('H');
bst.insertBST('D');
bst.insertBST('B');
bst.insertBST('M');
bst.insertBST('N');
bst.insertBST('A');
bst.insertBST('J');
bst.insertBST('E');
bst.insertBST('Q');
System.out.println("Binart Tree>>>");
bst.printBST();
System.out.println("Is There\"A\"?>>>");
TreeNode p1 = bst.searchBST('A');
if (p1 != null) {
System.out.println(p1.data + "탐색 성공");
}
else {
System.out.println("탐색 실패");
}
System.out.println("Is There\"Z\"?>>>");
TreeNode p2 = bst.searchBST('Z');
if (p2 != null) {
System.out.println(p2.data + "탐색 성공");
}
else {
System.out.println("탐색 실패");
}
}
}
'Algorithm > Algorithm Practice' 카테고리의 다른 글
[프로그래머스] 짝지어 제거하기 (Javascript) (0) | 2021.06.21 |
---|---|
프로그래머스 -7 완주하지 못한 선수 (Java) (0) | 2020.03.27 |
프로그래머스 -6 정수 내림차순으로 배치하기(Java) (0) | 2020.02.29 |
프로그래머스 -5 모의고사(Java) (0) | 2020.02.28 |
8. Recursion -3 (Java) (0) | 2020.02.28 |
댓글
최근에 올라온 글
최근에 달린 댓글
TAG
- 20200428
- 20200417
- 20200427
- chapter7
- 생활코딩리눅스
- 20200504
- 20200317
- 20200415
- 20200425
- 20200624
- 20200622
- likelion
- 20200403
- 20200423
- 20200512
- 20200502
- 20200804
- 20200421
- 20200319
- 20200420
- 20200510
- 백준
- 20200424
- 20200429
- 20201204
- 20200406
- 20200503
- 20200413
- 20200330
- chapter8
- Total
- Today
- Yesterday