-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTree.java
More file actions
69 lines (56 loc) · 1.79 KB
/
Copy pathBinaryTree.java
File metadata and controls
69 lines (56 loc) · 1.79 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
package project;
class TNode{
int data;
TNode left, right;
public TNode(int data){
this.data=data;
this.left = this.right = null;
}
}
public class BinaryTree{
TNode root;
//Tree Traversals
public void inorder(TNode node){
if (node==null) return;
inorder(node.left);
System.out.print(node.data+ "-->");
inorder(node.right);
}
public void preorder(TNode node){
if (node==null) return;
System.out.print(node.data+ "-->");
preorder(node.left);
preorder(node.right);
}
public void postorder(TNode node){
if (node==null) return;
postorder(node.left);
postorder(node.right);
System.out.print(node.data+ "-->");
}
public int findMax(TNode node){
if (node==null) return Integer.MIN_VALUE;
int left_max=findMax(node.left);
int right_max= findMax(node.right);
return Math.max(node.data, Math.max(left_max,right_max));
}
public int findMin(TNode node){
if (node==null) return Integer.MAX_VALUE;
int left_min=findMin(node.left);
int right_min=findMin(node.right);
return Math.min(node.data, Math.min(left_min,right_min));
}
public boolean search(TNode node, int key){
if (node==null) return false;
if (node.data==key) return true;
return search(node.left, key) || search(node.right,key);
}
private boolean isBSTUtil(TNode node, int min, int max){
if (node==null) return true;
if (node.data<=min || node.data>=max) return false;
return isBSTUtil(node.left, min,node.data) && isBSTUtil(node.right,node.data,max);
}
public boolean isBST(TNode node){
return isBSTUtil(node, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
}