-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkthSmallestValue.java
More file actions
42 lines (38 loc) · 1.09 KB
/
kthSmallestValue.java
File metadata and controls
42 lines (38 loc) · 1.09 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
//Queue implementation
class Solution {
int min=Integer.MIN_VALUE;
public int kthSmallest(TreeNode root, int k) {
Deque<TreeNode> q=new ArrayDeque<>();
q.add(root);
List<Integer> subsol=new ArrayList<>();
while(!q.isEmpty()){
int size=q.size();
TreeNode curr=q.remove();
subsol.add(curr.val);
for(int i=0;i<size;i++){
if(curr.right!=null){
q.add(curr.right);
}
if(curr.left!=null){
q.add(curr.left);
}
}
}
Collections.sort(subsol);
return subsol.get(k-1);
}
}
//inorder traversal Here the nodes are already in a sorted order
class Solution {
List<Integer> subsol=new ArrayList<>();
public int kthSmallest(TreeNode root, int k) {
inorder(root);
return subsol.get(k-1);
}
private void inorder(TreeNode root){
if(root==null)return;
inorder(root.left);
subsol.add(root.val);
inorder(root.right);
}
}