Kth Smallest Element in a BST | Leetcode | Java | CODING INTERVIEW QUESTION

preview_player
Показать описание
Given the root of a binary search tree, and an integer k, return the kth (1-indexed) smallest element in the tree.

Input: root = [3,1,4,null,2], k = 1
Output: 1

Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3

Solution:-

class Solution {
public int kthSmallest(TreeNode root, int k) {
int []arr = new int[2]; //0 - currentIndex , 1- current index value
inOrderTraversal(root, k, arr);
return arr[1];

}

public void inOrderTraversal(TreeNode root, int k, int []arr) {
if(root == null) {
return;
}

if(++arr[0] == k) {
}
}
}

time complexity o(n)
Рекомендации по теме
Комментарии
Автор

Very good explanation sir.. keep up the good work.

pandeyrahul
visit shbcf.ru