Skip to main content

LeetCode Problem #230. Kth Smallest element in Binary Search Tree.

 

Problem Statement:

Given a binary search tree. Program should return Kth Smallest element in the binary search tree.
Suppose if the binary tree is represented as:
3,1,4,null, 2

Then 1st smallest element is 1, second smallest element is 2 and 3rd smallest element is 3.
 

Solution with Explanation:

  • The binary tree consists of elements in sorted order.
  • The easiest way of finding solution is insert the elements in the priority queue and then  pop out k-1 elements, then top element of the priority queue is the kth smallest element of the tree.
  • Optimized solution is doing in-order traversal and keeping track of the count of number of elements visited.
  •  After visiting the left most element of the binary tree, increase the count to 1 and traverse back in in-order manner and increase the count.
  • Whenever the count is reached to k return that element.

Complexity Explanation:

  • As the traversal is in-order, each node is visited only once.
  • The traversal continues till the Kth element is found.
  • So, the complexity of the above solution is O(K), where k is the kth smallest element asked for.

Code in C++

class Solution {
    int Traverse(TreeNode *root, int k, int &iter){
        if(!root)
            return -1;
        int val = Traverse(root->left, k, iter);
        if(val != -1)
            return val;
        ++iter;
        if(iter == k)
            return root->val;
       
        val = Traverse(root->right, k, iter);
       
        return val;
    }
public:
    int kthSmallest(TreeNode* root, int k) {
            int iter  = 0;
        return Traverse(root, k, iter);
    }
};


Comments

Post a Comment

Popular posts from this blog

Leet Code: Problem #710 Random Pick with Blacklist

Given a blacklist  B containing unique integers from [0, N) , write a function to return a uniform random integer from [0, N) which is NOT  in B . Optimize it such that it minimizes the call to system’s Math.random() . Note: 1 <= N <= 1000000000 0 <= B.length < min(100000, N) [0, N)  does NOT include N. See interval notation . Example 1: Input: ["Solution","pick","pick","pick"] [[1,[]],[],[],[]] Output: [null,0,0,0] Example 2: Input: ["Solution","pick","pick","pick"] [[2,[]],[],[],[]] Output: [null,1,1,1] Example 3: Input: ["Solution","pick","pick","pick"] [[3,[1]],[],[],[]] Output: [null,0,0,2] Example 4: Input: ["Solution","pick","pick","pick"] [[4,[2]],[],[],[]] Output: [null,1,3,1] Explanation of Input Syntax: The input is two lists: the subroutines called and their argume...

LeetCode: Problem #1402. Reducing Dishes

Problem Statement: A chef has collected the data on the review for his dishes. Our Chef will take just 1 unit of time to prepare a dish. Our job is to tell him the dishes he has to make in the order to achieve maximum benefit. The maximum benefit is calculated using the formula time[i] * (review ratings). Example 1: Input: reviews = [-1, -10, -9, 0, 5] Output: 14 Explanation: Considering the dishes in the order of -1, 0 ,5 the calculation will be (-1 * 1 + 0 * 2 + 5 * 3) = 14 Example 2: Input: reviews = [6,5,4] Output: 32 Explanation: Considering the dishes in the order of 4, 5, 6 the calculation will be (4 * 1 + 5 * 2 + 6 * 3) = 32 Approach to the solution: Sort the given reviews so that we can concentrate only on maximum benefited reviews. Make cumulative sums from the end. This will help in deciding till which we have to consider the summation. Now start from the end at add the previous array of cumulative sums until a negative number is encountered. We have to iterate in reverse or...

Creating Self Signed SSL Certificates for HTTPS Communication

Self Signed CA: Create Private Key for Self Signed CA openssl ecparam -genkey -name secp256r1 | openssl ec -out ca.key     Create CA Certificate for Self Signed CA openssl req -new -x509 -days 36500 -key ca.key -out ca.pem -subj "/C=IN/ST=Karnataka/L=Bengaluru/O=company name/OU=Prod Operations Department/CN=prodops .domain.com   Verify the content of CA certificate openssl x509 -in ca.pem -noout -text Client CERTIFICATE: CLIENT_ID="<Client-Product>" e.g. CLIENT_ID="ClientID" CLIENT_SERIAL="<Client-Release-Number>" e.g. CLIENT_SERIAL="6889" Create Private Key for Client openssl ecparam -genkey -name secp256r1 | openssl ec -out  ${CLIENT_ID}_${CLIENT_SERIAL}.key                   Generate the Certificate Signing Request CSR openssl req -new -key ${CLIENT_ID}_${CLIENT_SERIAL}.key -out ${CLIENT_ID}_${CLIENT_SERIAL}.csr -subj "/C=IN/ST=Karnataka/L=Bengalur...