-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeSearch.java
More file actions
105 lines (88 loc) · 2.8 KB
/
BinaryTreeSearch.java
File metadata and controls
105 lines (88 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package trees;
import java.util.LinkedList;
import java.util.Queue;
/**
*
* @author Vladimir Aca
*/
public class BinaryTreeSearch {
BinaryNode root;
public BinaryTreeSearch() {
this.root = null;
}
public void addNode(BinaryNode newNode, BinaryNode currentNode){
if(this.root == null){
this.root = newNode;
return;
}
if(currentNode.value > newNode.value){
if(currentNode.left == null){
currentNode.left = newNode;
}else{
this.addNode(newNode, currentNode.left);
}
}
if(currentNode.value < newNode.value){
if(currentNode.right == null){
currentNode.right = newNode;
}else{
this.addNode(newNode, currentNode.right);
}
}
}
public void getNodesByLevel(BinaryNode currentNode){
if(this.root == null){
return;
}
Queue<BinaryNode> queue = new LinkedList<>();
queue.add(currentNode);
while(!queue.isEmpty()){
BinaryNode parentNode = queue.poll();
System.out.print(parentNode.value + "\t");
if(parentNode.left != null){ queue.add(parentNode.left); }
if(parentNode.right != null){ queue.add(parentNode.right); }
}
}
public int getHeigh(BinaryNode currentNode){
if(this.root == null){
return 0;
}
int leftHeigh = 0;
int rightHeigh = 0;
if(currentNode.left != null){
leftHeigh = getHeigh(currentNode.left);
}
if(currentNode.right != null){
rightHeigh = getHeigh(currentNode.right);
}
return Math.max(leftHeigh, rightHeigh) + 1;
}
public BinaryNode createNode(int value){
return new BinaryNode(value);
}
public BinaryNode getRoot(){
return this.root;
}
public void search(int targetValue, BinaryNode currentNode ){
if(currentNode.value == targetValue){
System.out.println("The node EXIST");
return;
}
if(currentNode.value > targetValue){
if(currentNode.left != null){
this.search(targetValue, currentNode.left);
}else{System.out.println("NO DATA");}
return;
}
if(currentNode.value < targetValue){
if(currentNode.right != null){
this.search(targetValue, currentNode.right);
}else{System.out.println("NO DATA");}
}
}
}