-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray to BST.java
More file actions
101 lines (86 loc) · 2.91 KB
/
Copy pathArray to BST.java
File metadata and controls
101 lines (86 loc) · 2.91 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
//{ Driver Code Starts
import java.io.*;
import java.util.*;
class Node {
int data;
Node left, right;
Node(int item) {
data = item;
left = right = null;
}
}
public class Main {
public static boolean isValidBSTUtil(Node node, long lower, long upper) {
if (node == null) return true;
if (node.data <= lower || node.data >= upper) return false;
return isValidBSTUtil(node.left, lower, node.data) &&
isValidBSTUtil(node.right, node.data, upper);
}
public static boolean isValidBST(Node root) {
return isValidBSTUtil(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public static int height(Node root) {
if (root == null) return 0;
int leftHeight = height(root.left);
int rightHeight = height(root.right);
if (leftHeight == -1 || rightHeight == -1 ||
Math.abs(leftHeight - rightHeight) > 1) {
return -1;
}
return Math.max(leftHeight, rightHeight) + 1;
}
public static boolean isBalanced(Node root) { return height(root) != -1; }
public static void inorder(Node root, List<Integer> v) {
if (root == null) return;
inorder(root.left, v);
v.add(root.data);
inorder(root.right, v);
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine().trim());
while (T-- > 0) {
String input = br.readLine().trim();
String[] inputArr = input.split(" ");
int[] arr = new int[inputArr.length];
for (int i = 0; i < inputArr.length; i++) {
arr[i] = Integer.parseInt(inputArr[i]);
}
Solution obj = new Solution();
Node root = obj.sortedArrayToBST(arr);
List<Integer> v = new ArrayList<>();
inorder(root, v);
int[] vrr = v.stream().mapToInt(Integer::intValue).toArray();
boolean isBST = isValidBST(root);
if (!isBST || !Arrays.equals(vrr, arr)) {
System.out.println("false");
continue;
}
boolean balanced = isBalanced(root);
if (balanced) {
System.out.println("true");
} else {
System.out.println("false");
}
}
}
}
// } Driver Code Ends
// User function Template for Java
class Solution {
Node bstTree(int nums[], int left, int right){
if(left>right){
return null;
}
int mid=left+(right-left)/2;
Node root=new Node(nums[mid]);
root.left=bstTree(nums, left, mid-1);
root.right=bstTree(nums, mid+1,right);
return root;
}
public Node sortedArrayToBST(int[] nums) {
// Code here
Node root=bstTree(nums, 0, nums.length-1);
return root;
}
}