230. Kth Smallest Element in a BST

PHOTO EMBED

Thu Mar 16 2023 11:41:32 GMT+0000 (Coordinated Universal Time)

Saved by @Ranjan_kumar #c++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

//BFS Travesal

class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        vector<int> v;
        queue<TreeNode*> q;
        TreeNode* p;
        q.push(root);
        
        while(!q.empty())
        {
            p=q.front();
            q.pop();
            ///int p2=p->val;
            v.push_back(p->val);
            if(p->left) q.push(p->left);
            if(p->right) q.push(p->right);
        }
        sort(v.begin(), v.end());
        return v[k-1];
    }
};

//Inorder traversal

class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        vector<int> v;
        queue<TreeNode*> q;
        TreeNode* p;
        q.push(root);
        
        while(!q.empty())
        {
            p=q.front();
            q.pop();
            ///int p2=p->val;
            v.push_back(p->val);
            if(p->left) q.push(p->left);
            if(p->right) q.push(p->right);
        }
        sort(v.begin(), v.end());
        return v[k-1];
    }
};
content_copyCOPY

https://leetcode.com/problems/kth-smallest-element-in-a-bst/