L45. K-th Smallest/Largest Element in BST

แชร์
ฝัง
  • เผยแพร่เมื่อ 31 ธ.ค. 2024

ความคิดเห็น • 194

  • @takeUforward
    @takeUforward  3 ปีที่แล้ว +73

    In largest, we can traverse right node left and then apply the same logic..
    You can also contribute an article for this video: takeuforward.org/contribute/help-us-grow-takeuforward/
    Will be continuing with this setup, as youtube tends to push videos with human appearance!!

    • @solaris413
      @solaris413 3 ปีที่แล้ว +1

      any plan of hiring interns for ur site and what will be the requirements

    • @ananthalakshmi
      @ananthalakshmi 7 หลายเดือนก่อน

      @takeUforward
      Thank you so much anna🤩🤩🤩🤩🤩🤩.....
      keep doing more and more videos anna....
      For finding smallest using #InorderMorrisTraversal (left, root, right) :-
      code🔥🔥🔥🔥🔥🔥:-
      int kthSmallest(TreeNode* root, int k) {
      TreeNode* cur = root;
      int ans;
      int count =0;
      while(cur != nullptr){

      if(cur -> left == nullptr){
      count += 1;
      if(count == k){

      ans= cur -> val;

      }

      cur = cur -> right;

      }
      else{
      TreeNode* prev = cur -> left;
      while(prev -> right != nullptr && prev -> right != cur){
      prev = prev -> right;

      }
      if(prev -> right== nullptr){
      prev -> right = cur;
      cur = cur -> left;
      }
      else{
      count += 1;
      prev -> right = nullptr;
      if(count == k){
      ans =cur -> val;
      }

      cur = cur -> right;

      }
      }
      }
      return ans;
      }
      for finding largest using #reversalInorderMorrisTraversal (right root left) :-
      code🔥🔥🔥🔥🔥🔥:-
      int kthLargest(Node* root, int k) {
      Node* cur = root;
      int ans;
      int count =0;
      while(cur != nullptr){

      if(cur -> right == nullptr){
      count += 1;
      if(count == k){

      ans= cur -> data;

      }

      cur = cur -> left;

      }
      else{
      Node* prev = cur -> right;
      while(prev -> left != nullptr && prev -> left != cur){
      prev = prev -> left;

      }
      if(prev -> left== nullptr){
      prev -> left = cur;
      cur = cur -> right;
      }
      else{
      count += 1;
      prev -> left = nullptr;
      if(count == k){
      ans =cur -> data;
      }

      cur = cur -> left;

      }
      }
      }
      return ans;
      }

  • @deanwinchester8691
    @deanwinchester8691 3 ปีที่แล้ว +278

    for kth largest we can do a reverse inorder kind of thing: RIGHT ROOT LEFT with the counter logic

  • @GauravKumar-dw2ml
    @GauravKumar-dw2ml 2 ปีที่แล้ว +48

    For kth largest just do the reverse in-order , and print the kth element. Bcoz this will lead to decreasing order.

    • @secondarypemail7181
      @secondarypemail7181 2 ปีที่แล้ว +1

      This is the first solution that comes in the mind

  • @mohdhammadsiddiqui7598
    @mohdhammadsiddiqui7598 2 ปีที่แล้ว +38

    Just a small observation In the kth largest problem if we take reverse inorder than the elements are sorted in descending fashion, so we can directly get kth largest element

    • @yagniktalaviya2146
      @yagniktalaviya2146 2 ปีที่แล้ว +2

      sahi hai!!

    • @amanali9501
      @amanali9501 2 ปีที่แล้ว +5

      correct ✅

    • @peacefullife2071
      @peacefullife2071 3 หลายเดือนก่อน

      Of course ! but the optimal solution as he said is not to use any extra space. That's why n-k logic comes.

  • @kushagraahire1871
    @kushagraahire1871 ปีที่แล้ว +19

    JAVA Solution for Smallest Kth: -
    class Solution {
    private int count = 0;
    private int result = 0;

    public int kthSmallest(TreeNode root, int k) {
    traverse(root, k);
    return result;
    }

    private void traverse(TreeNode node, int k) {
    if (node == null) {
    return;
    }
    traverse(node.left, k);
    count++;
    if (count == k) {
    result = node.val;
    return;
    }
    traverse(node.right, k);
    }
    }
    JAVA Solution for Largest Kth: -
    class Solution
    {
    int ans = 0;
    int count = 0;
    public int kthLargest(Node root,int k)
    {
    traversal(root,k);
    return ans;
    }
    public void traversal(Node root, int k){
    if(root == null) return;
    traversal(root.right,k);
    count++;
    if(count == k){
    ans = root.data;
    return;
    }
    traversal(root.left,k);
    }
    }

  • @parikshitsinghrathore6130
    @parikshitsinghrathore6130 2 ปีที่แล้ว +12

    we can also do this by doing inorder traversal (this will make the vector in sorted format) and then finding the kth smallest no. in it. time complexity will be O(n) + O(n)

  • @vaishnavigour5777
    @vaishnavigour5777 2 ปีที่แล้ว +20

    for Kth largest it should be (n-k+1)th smallest

  • @stith_pragya
    @stith_pragya 7 หลายเดือนก่อน +1

    Understood.............Thank You So Much for this wonderful video.....🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

  • @AlokSingh-qj3hf
    @AlokSingh-qj3hf 12 วันที่ผ่านมา

    class Solution(object):

    def __init__(self):
    self.c = 0
    self.r = 0
    def kthSmallest(self, root, k):
    """
    :type root: TreeNode
    :type k: int
    :rtype: int
    """
    def inor(k,c,root):
    if root==None:
    return
    inor(k,c,root.left)
    self.c+=1
    if k==self.c:
    self.r=root.val
    return
    inor(k,c,root.right)

    inor(k,self.c,root)
    return self.r

  • @akshaychavan5511
    @akshaychavan5511 7 หลายเดือนก่อน +1

    For the kth largest question, we don't even need to make the adjustment as (n-k)th smallest element. We can simply reverse the order of traversal as - Right - Root - Left

    • @ChayK11
      @ChayK11 5 หลายเดือนก่อน

      so its post order right?

    • @wttc4
      @wttc4 5 หลายเดือนก่อน

      @@ChayK11 no, postorder traversal is: left->right->root

  • @xavier6955
    @xavier6955 3 ปีที่แล้ว +13

    Man, I was stuck with this problem yesterday coz I didn't get what I have to find from all the tutorials online. Striver explained it in 2 mins.🔥

    • @geekaffairs6475
      @geekaffairs6475 3 ปีที่แล้ว +5

      I can't believe you are in I.T

    • @xavier6955
      @xavier6955 3 ปีที่แล้ว +9

      @@geekaffairs6475 I am not in IT, I am the IT.

    • @utkarshverma2604
      @utkarshverma2604 3 ปีที่แล้ว +2

      @@geekaffairs6475 samw bro ye banda har jagah h

  • @abcsumits
    @abcsumits 2 ปีที่แล้ว +2

    why not we visit directly right first and left after while treversing for k th max. :) it will be done in one treversal

  • @aayushprajapati347
    @aayushprajapati347 3 ปีที่แล้ว +21

    I think Kth largest element can be done in single traversal. By using reverse inorder traversal i.e.(Right-Node-Left) .Then we can easily figure out kth largest element in single traversal.
    Just require few modification in code:
    int kthLargest(TreeNode* root, int k) {
    stack st;
    TreeNode* node = root;
    int cnt = 0;
    while(true) {
    if(node != NULL) {
    st.push(node);
    node = node->right;
    }
    else {

    if(st.empty() == true) break;
    node = st.top();
    st.pop();

    cnt++;
    if(cnt == k) return node->val;
    node = node->left;
    }
    }
    return -1;
    }

  • @budhadityachatterjee6270
    @budhadityachatterjee6270 3 ปีที่แล้ว +9

    Diwali pe DP Series aa rha hain kya ?

  • @mridulsarma9022
    @mridulsarma9022 3 ปีที่แล้ว +9

    Bhaiya it may be n+1-k th element..as for if we have 4 nodes then 2nd element from last will be 4+1-2 th i.e 3rd node.thats why I am saying about this confusion

  • @sahil_bagde
    @sahil_bagde 2 หลายเดือนก่อน

    C++ Code :
    class Solution {
    public:
    vectorans;
    void inorder(TreeNode* root){
    if(root == NULL ) return;
    inorder(root->left);
    ans.push_back(root->val);
    inorder(root->right);
    }
    int kthSmallest(TreeNode* root, int k) {
    inorder(root);
    return ans[k-1];
    }
    };

  • @ishankbansal9239
    @ishankbansal9239 3 ปีที่แล้ว +13

    OP Video Quality and Setup🔥
    Using Morris Inorder Traversal
    TC - O(N), SC - O(1)
    class Solution {
    public:
    int kthSmallest(TreeNode* root, int k) {
    int count = 0;
    int ans;
    TreeNode* curr = root;
    while(curr){
    if(curr->left == NULL){
    count++;
    if(count == k){
    ans = curr->val;
    }
    curr = curr->right;
    }
    else{
    TreeNode* prev = curr->left;
    while(prev->right && prev->right != curr){
    prev = prev->right;
    }
    if(prev->right == NULL){
    prev->right = curr;
    curr = curr->left;
    }
    else{
    count++;
    prev->right = NULL;
    if(count == k){
    ans = curr->val;
    }
    curr = curr->right;
    }
    }
    }
    return ans;
    }
    };

    • @Avinashkumar-km2cl
      @Avinashkumar-km2cl 2 ปีที่แล้ว

      Bro, I have written the same code as yours but I am having a doubt. why we are not breaking the loop..? we got the required solution. I tried this but it showed an error. if possible then please clear my doubt.
      @take U forward
      Code:
      class Solution {
      public:
      int kthSmallest(TreeNode* root, int k)
      {
      int i=0;
      int ans=0;
      TreeNode*curr;
      while(root)
      {
      if(!root->left)
      {
      i++;
      if(i==k)
      {
      ans= root->val;
      break;
      }

      root=root->right;
      }
      else
      {
      curr=root->left;
      while(curr->right && curr->right!=root)
      curr=curr->right;
      if(curr->right==root)
      {
      curr->right=NULL;
      i++;
      if(i==k)
      {
      ans= root->val;
      break;
      }
      root=root->right;
      }
      else
      {
      curr->right=root;
      root=root->left;
      }
      }
      }
      return ans;
      }
      };

    • @mayankkumar6067
      @mayankkumar6067 2 ปีที่แล้ว

      @@Avinashkumar-km2cl Hey , i am also trying to break out of loop but getting error, if you got an answer then please help

    • @factfactorial632
      @factfactorial632 2 ปีที่แล้ว +7

      @@Avinashkumar-km2cl because in morris traversal you did create threads and now you are not breaking it

    • @akshitsangwan_
      @akshitsangwan_ 2 ปีที่แล้ว

      @@factfactorial632 So we have to traverse the whole tree and can't break the loop, even if we got the answer at the very start!??

    • @mukib_khan_
      @mukib_khan_ 2 ปีที่แล้ว

      @@akshitsangwan_ got the answer anyone?

  • @divyanshusingh2396
    @divyanshusingh2396 2 ปีที่แล้ว +2

    If we use inorder then there will be no need of sorting… because inorder of bst is already sorted

  • @shantanugupta-oz1dx
    @shantanugupta-oz1dx 5 หลายเดือนก่อน

    Thank you for the simple explanation

  • @ankittjindal
    @ankittjindal 3 ปีที่แล้ว +2

    Ab yhi request h bhaiya..... recursion, backtracking,dp k v ase hii series alg alg dsa k upr lekr aaiye!! plzzz bhaiyaaa ❤️❤️❤️🥺🥺🙏🙏🙏

    • @mridulsarma9022
      @mridulsarma9022 3 ปีที่แล้ว

      Check the playlists..I hope you will get all of those.

    • @ankittjindal
      @ankittjindal 3 ปีที่แล้ว

      @@mridulsarma9022 nii bro bat wo nii h bhaiyaaa ne toh usme syd sde sheet ka sb video explain qsn sb ka dala hua h n ...
      .

    • @ankittjindal
      @ankittjindal 3 ปีที่แล้ว

      @@mridulsarma9022 toh wo beginner recursion ye sb me kse dkh skta h koi v ...hm ye bol rhe ki in sb ka dsa ka v ase hii playlist bnaye ...jse ki aapne graph,tree ka bnya h ye bol rhe h hm . bro.....
      Wse wo sb playlist ksa h qsns sb ka maine nii dkha h pura...kyuki meko abhi wo sb utna nii ata bhaii mere!!

  • @pranshumehta3228
    @pranshumehta3228 2 ปีที่แล้ว +7

    If we do simple recursive inorder traversal then time complexity should be O(k) because we don't need to go further after getting kth smallest
    Is that correct ?

    • @dianafarhat9479
      @dianafarhat9479 2 ปีที่แล้ว +3

      Yes, but at most K is equal to n (e.g. k=n) . So, the worst case scenario is O(n).

    • @imPriyansh77
      @imPriyansh77 9 หลายเดือนก่อน

      worst case scenario would be O(N)

  • @arjunkurariya2235
    @arjunkurariya2235 3 ปีที่แล้ว +4

    Best Series ever seen❤️❤️. Is CP necessary for CODING ROUND..??? PLS ANSWER 🙏🙏🙏

  • @ahustler110
    @ahustler110 หลายเดือนก่อน +1

    but why will we sort?? inorder of bst is already sorted array in incresing order

  • @shivangisrivastava1158
    @shivangisrivastava1158 3 ปีที่แล้ว +1

    Thodi mehnat lag gyi Morris implement krne me, but golden content!

    • @Stickman-rz9nu
      @Stickman-rz9nu 8 หลายเดือนก่อน

      can you please provide the morris traversal solution ? i'm getting stack overflow error 🥹🥹

  • @mrrealnobody4382
    @mrrealnobody4382 4 วันที่ผ่านมา

    What about the Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?

  • @prasannamalatesha3887
    @prasannamalatesha3887 ปีที่แล้ว

    Great explanation bro. Perfectly explained all the possible solutions for this problem

  • @alesblaze4745
    @alesblaze4745 2 ปีที่แล้ว +4

    thanks mate! this was really challenging & fun solving, tried to implement it using Moris Traversal without revising and took a while to implement but was able to implement it successsfully!

    • @parthsalat
      @parthsalat 2 ปีที่แล้ว +1

      Nice dp...Daffodils, isn't it?

  • @AbhishekPandey-dj2eo
    @AbhishekPandey-dj2eo 11 หลายเดือนก่อน

    Keep doing this GOOD WORK

  • @akshayteja2864
    @akshayteja2864 6 หลายเดือนก่อน +2

    C++ Solution
    class Solution {
    public:
    void helper(TreeNode *root,int &k,int &count,int &ans)
    {
    if(root==NULL)
    return;
    helper(root->left,k,count,ans);
    count++;
    if(count==k)
    ans=root->val;
    helper(root->right,k,count,ans);
    }
    int kthSmallest(TreeNode* root, int k) {
    int count=0,ans;
    helper(root,k,count,ans);
    return ans;
    }
    };

  • @abhijitroy1958
    @abhijitroy1958 2 ปีที่แล้ว +2

    when you were explaining the brut ,i accidentally coded the optimal by using morries xd

  • @ChetanSingh-zp4ct
    @ChetanSingh-zp4ct 2 ปีที่แล้ว +11

    LeetCode 230:
    class Solution {
    public:
    int count = 0;
    int ans;
    void inorder(TreeNode* root, int k){
    if(!root)return;
    inorder(root->left,k);

    if(++count==k){
    ans = root->val;
    return;
    }
    inorder(root->right,k);
    }
    int kthSmallest(TreeNode* root, int k) {
    inorder(root,k);
    return ans;

    }
    };

    • @herculean6748
      @herculean6748 2 ปีที่แล้ว +1

      Thanks bro!

    • @VishalGupta-xw2rp
      @VishalGupta-xw2rp 2 ปีที่แล้ว

      We can also add condition like.... To increase the count value only when there's some value there and not NULL like
      if(root)
      if (++count==k)

    • @yativishnoi5110
      @yativishnoi5110 2 ปีที่แล้ว

      @@VishalGupta-xw2rp But we already checked for the root, then root can't be null. So no need to check for it.

    • @only_for_fun1234r
      @only_for_fun1234r ปีที่แล้ว

      If (ans!=-1) return ans; will it save something?

  • @vishious14
    @vishious14 ปีที่แล้ว

    List result;
    public int kthSmallest(TreeNode root, int k) {
    result = new ArrayList();
    inorder(root,k);
    return result.get(result.size()-1);
    }
    private void inorder(TreeNode root,int k){
    if(root==null) return;
    inorder(root.left,k);
    if(result.size()==k) return;
    result.add(root.val);
    inorder(root.right,k);
    }

  • @rakhshanahmad8057
    @rakhshanahmad8057 9 หลายเดือนก่อน

    Great explanation. Those last approaches are great.

  • @Usurperhk
    @Usurperhk 3 ปีที่แล้ว +3

    Bhaiya this is the best evolution of your videos. Left side knowledge right side legend. It's f***king awesome bhaiya. 🙂🙂🙂

  • @sagarkakkar4150
    @sagarkakkar4150 ปีที่แล้ว +1

    kth element can be found out in O(N) using quick sort

    • @mayanksardana3179
      @mayanksardana3179 ปีที่แล้ว

      quick sort is nlogn bro

    • @sagarkakkar4150
      @sagarkakkar4150 ปีที่แล้ว

      We just have to run quicksort partition function one time to find kth element

    • @sagarkakkar4150
      @sagarkakkar4150 ปีที่แล้ว

      Not one time but a few times
      It's called quick select

  • @tech_wizard9315
    @tech_wizard9315 3 ปีที่แล้ว +5

    Is your tree series enough for DSA beginners for Tech interviews of companies like Microsoft , linkedin etc?

  • @aryansinha1818
    @aryansinha1818 2 ปีที่แล้ว

    06:40 Largest

  • @izumi7754
    @izumi7754 8 หลายเดือนก่อน +3

    you said u have provided the code in the description but it isnt there, this is a very common occurence when i look at descrptions i never find the codes, am i looking at the wrong place or is he just not attaching the code

    • @anishaa3298
      @anishaa3298 8 หลายเดือนก่อน +1

      you are welcome:
      class Solution {
      int count=0;
      int result;
      public int kthSmallest(TreeNode root, int k) {
      if (root==null)
      {
      return 0;
      }
      inOrderTraversal(root,k);
      return result;

      }
      public void inOrderTraversal(TreeNode root, int k)
      {
      if (root==null)
      {
      return ;
      }
      inOrderTraversal(root.left,k);
      count++;
      if (count==k)
      {
      result =root.val;
      return;
      }
      inOrderTraversal(root.right,k);
      }
      }

    • @rushidesai2836
      @rushidesai2836 6 หลายเดือนก่อน

      He's providing quality content for free, and still you are complaining for a small mistake?

  • @tanveer.shaikh
    @tanveer.shaikh 2 ปีที่แล้ว +1

    I did not understand why you need to sort the elements, if we do inorder traversal we could do it in o(n),

  • @MadhavGupta-fi2tu
    @MadhavGupta-fi2tu ปีที่แล้ว +6

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

    • @DeepakKumar-mn8yi
      @DeepakKumar-mn8yi ปีที่แล้ว

      we can add if(c>k) return;
      before root->right;

  • @KnowledgeofEverything
    @KnowledgeofEverything 3 ปีที่แล้ว +2

    New setup is good .... But I don't think it matters much .... For me your content matters more and it's great

  • @ANANDKUMAR-hd8mj
    @ANANDKUMAR-hd8mj 17 วันที่ผ่านมา

    nice concept

  • @aryanchaurasia1081
    @aryanchaurasia1081 ปีที่แล้ว

    For kth largest we can do right root left traversal

  • @sushantbhosale5792
    @sushantbhosale5792 3 ปีที่แล้ว +1

    Striver bhaiya aur kitne videos baki he playlist ke when it will be completed??

  • @codeman3828
    @codeman3828 8 หลายเดือนก่อน

    Understood. Thanks

  • @mayankbisht1277
    @mayankbisht1277 3 หลายเดือนก่อน

    For largest why not do [Right,Node,Left] ?

  • @JEAnandkumar
    @JEAnandkumar 2 ปีที่แล้ว +1

    One correction:
    k th largest element = (n-k+1)th smallest element

    • @parthsalat
      @parthsalat 2 ปีที่แล้ว

      Exactly! I was thinking about this

  • @sparshsharma3150
    @sparshsharma3150 3 ปีที่แล้ว +9

    Striver's video explanation --- mind blown
    Striver's video explanation with face cam ---- mind blown ultra pro max 😂😂

  • @ankitkr09
    @ankitkr09 3 ปีที่แล้ว +1

    Agar ek din pehle upload kr deta bhai toh mera amazon clear ho jata..

  • @reddysasikiran315
    @reddysasikiran315 3 หลายเดือนก่อน

    what if duplicate elements are there

  • @abhinavkumar6584
    @abhinavkumar6584 2 ปีที่แล้ว +2

    shouldn't kth largest should be n-k+1 ??? Anyone?

  • @dingo_5998
    @dingo_5998 2 ปีที่แล้ว +1

    Thank you bhaiya Meet me in G.😎😎😎😎

  • @shubamgoswami
    @shubamgoswami 3 ปีที่แล้ว +1

    striver video is like the latest iPhone top notch but with facecam It is like u get air pods and fast charger in the box with the latest apple cloth.

  • @santoshkumarroy5070
    @santoshkumarroy5070 2 ปีที่แล้ว

    explanation on point . loved it bhaiya

  • @vaalarivan_p
    @vaalarivan_p ปีที่แล้ว

    4:25

  • @UECAshutoshKumar
    @UECAshutoshKumar ปีที่แล้ว +1

    Thank you sir

  • @AnandSingh-zm5cm
    @AnandSingh-zm5cm 3 ปีที่แล้ว

    Why we need to sort?Inorder always gave sorted elements

    • @imPriyansh77
      @imPriyansh77 9 หลายเดือนก่อน

      we need to sort only if we're implementing preorder, postorder or level order.

  • @isheep9025
    @isheep9025 ปีที่แล้ว +1

    morris traversal for kth largest and "dec" vector in program stores decreasing order of values
    /**
    * 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) {}
    * };
    */
    class Solution {
    public:
    int kthSmallest(TreeNode* root, int k) {
    int cnt=0;
    TreeNode * curr=root;
    int ans;
    vector dec;
    while(curr!=NULL)
    {
    if(curr->right==NULL)
    {
    cnt++;
    if(cnt==k)
    {
    ans=curr->val;

    }
    dec.push_back(curr->val);
    curr=curr->left;
    }
    else{
    TreeNode * temp=curr->right;
    while(temp->left!=NULL && temp->left!=curr)
    temp=temp->left;
    if(temp->left==NULL){
    temp->left=curr;
    curr=curr->right;}
    else{
    temp->left=NULL;
    cnt++;
    if(cnt==k)
    {
    ans=curr->val;
    }
    dec.push_back(curr->val);
    curr=curr->left;
    }
    }
    }
    for(int ele:dec)
    cout

  • @geekaffairs6475
    @geekaffairs6475 3 ปีที่แล้ว +1

    Amazing explanation.

  • @hitenrana4775
    @hitenrana4775 2 ปีที่แล้ว +2

    One of my friend's got rejection in amazon with morris traversal approach. How can you do this in only logN complexity? This was asked in amazon interview and the approach doesn't make sense. It was written that we can store a count of left subtree nodes while generating the tree. Generation will take o(n) itself then how can it be logN.

    • @ideepakpandey
      @ideepakpandey 2 ปีที่แล้ว

      complexity will be o(n) not logn, space complexity will be o(1)

    • @hitenrana4775
      @hitenrana4775 2 ปีที่แล้ว

      @@ideepakpandey thats what i said read the comment again

    • @Rajat_maurya
      @Rajat_maurya 2 ปีที่แล้ว +1

      GFG article hai
      Method 2: Augmented Tree Data Structure (O(h) Time Complexity and O(h) auxiliary space)
      The idea is to maintain the rank(count) of each node. We can keep track of elements in the left subtree of every node while building the tree. Since we need the K-th smallest element, we can maintain the number of elements of the left subtree in every node.
      Assume that the root is having ‘lCount’ nodes in its left subtree. If K = lCount + 1, root is K-th node. If K < lCount + 1, we will continue our search (recursion) for the Kth smallest element in the left subtree of root. If K > lCount + 1, we continue our search in the right subtree for the (K - lCount - 1)-th smallest element. Note that we need the count of elements in the left subtree only.

  • @naman_goyal
    @naman_goyal 3 ปีที่แล้ว +1

    Ab maza aayega na bidu💝👍

  • @lavanyaprakashjampana933
    @lavanyaprakashjampana933 2 ปีที่แล้ว

    we love your content and we love you...🖤

  • @anshulgoel1940
    @anshulgoel1940 ปีที่แล้ว

    Can we do R N L for Kth largest using morris? I just tried a psuedo code seems possible.

  • @sakshamsengar9798
    @sakshamsengar9798 2 ปีที่แล้ว +1

    shoudn't it be for kth largest we need n-k+1th smallest?????

  • @adityapandey23
    @adityapandey23 3 หลายเดือนก่อน

    Understood

  • @pvenkatesh3690
    @pvenkatesh3690 หลายเดือนก่อน

    It's looking kth largest approach is wrong. it should be Kth largest = (N-K) + 1 smallest element

  • @KartikeyTT
    @KartikeyTT 4 หลายเดือนก่อน

    tysm sir

  • @Anonymous-uj3jx
    @Anonymous-uj3jx 2 ปีที่แล้ว

    Understood thanks :)

  • @sankalpietechtips
    @sankalpietechtips ปีที่แล้ว

    Thanks bro, you did good

  • @VIRAJBHOSLE
    @VIRAJBHOSLE ปีที่แล้ว +3

    need to improve this video. not very clear

  • @shouvikdatta6831
    @shouvikdatta6831 3 ปีที่แล้ว

    Man, after DP, make a series on stack & queue..

  • @Girish415
    @Girish415 3 ปีที่แล้ว

    Thank you

  • @harshitjaiswal9439
    @harshitjaiswal9439 10 หลายเดือนก่อน

    understood.

  • @ShubhanshuG007
    @ShubhanshuG007 ปีที่แล้ว

    Using Morris Traversal
    class Solution {
    public:
    Node* inorder(Node* root, int &K){
    Node* curr = root;
    while(curr != NULL){
    if(curr->left == NULL){
    K--;
    if(K==0) return curr;
    curr = curr->right;
    }
    else{
    Node* prev = curr->left;
    while(prev->right != NULL && prev->right != curr){
    prev = prev->right;
    }

    if(prev->right == NULL){
    prev->right = curr;
    curr = curr->left;
    }
    else{
    prev->right = NULL;
    K--;
    if(K==0) return curr;
    curr = curr->right;
    }
    }
    }
    return NULL;
    }
    // Return the Kth smallest element in the given BST
    int KthSmallestElement(Node *root, int K) {
    // add code here.
    Node* res = inorder(root, K);
    if( res != NULL)
    return res->data;
    return -1;

    }
    };

    • @divyanshjain7999
      @divyanshjain7999 7 หลายเดือนก่อน +1

      it isnt giving error on leetcode?

  • @mohitsingh7793
    @mohitsingh7793 2 ปีที่แล้ว

    kth largest=(n-k+1)th smallest element.

  • @chiragbansod8252
    @chiragbansod8252 9 หลายเดือนก่อน

    understood

  • @sundarbsr4275
    @sundarbsr4275 ปีที่แล้ว

    understand ❤

  • @aditya-st1sv
    @aditya-st1sv 3 ปีที่แล้ว

    #Striveronfire 🔥🔥🔥

  • @saurabhgautam2697
    @saurabhgautam2697 2 ปีที่แล้ว

    Can anyone Please ,explain to me why is it showing run-time error ,I m trying to do inorder morris traversal
    class Solution {
    public:
    int kthSmallest(TreeNode* root, int k) {

    int freq=0;
    TreeNode* ans;

    if(root==NULL)return 0;

    TreeNode* curr=root;

    while(curr!=NULL){

    if(curr->left==NULL){
    freq++;
    if(freq==k){
    return curr->val;
    break;
    }


    curr=curr->right;
    }
    else{

    TreeNode* temp=curr->left;

    while(temp->right!=NULL && temp->right!=curr)
    temp=temp->right;

    if(temp->right==NULL){
    temp->right=curr;
    curr=curr->left;
    }
    else{
    //temp->right=NULL;

    freq++;
    if(freq==k){
    return curr->val;
    }
    temp->right=NULL;
    curr=curr->right;
    }
    }
    }
    return -1;
    }
    };

    • @adityan5302
      @adityan5302 2 ปีที่แล้ว

      else{
      //temp->right=NULL;

      freq++;
      if(freq==k){
      return curr->val;
      }
      temp->right=NULL;
      curr=curr->right;
      Here you are trying to edit the BST, maybe that's the issue

    • @saarthaksharma9555
      @saarthaksharma9555 ปีที่แล้ว

      You have to return integer answer but you are returning 'node' so just put the condition that when freq==k,
      ans=cur->val;
      and at the end return ans;

    • @saarthaksharma9555
      @saarthaksharma9555 ปีที่แล้ว

      and don't apply the break statement as it will give stack overflow error because of the morris threading

    • @ThoNguyenuc-pz3yr
      @ThoNguyenuc-pz3yr ปีที่แล้ว

      @@saarthaksharma9555 yeah, if we use break or return the construct of binary tree will change and cause to overflow, we have to run until the curr is null

  • @roopeshn3301
    @roopeshn3301 2 ปีที่แล้ว

    Understood

  • @mehulmorker258
    @mehulmorker258 2 ปีที่แล้ว

    C++ code link opens Javacode and Java code link opens C++ code. Edit That Bro 😇

  • @saumyakarnwal7551
    @saumyakarnwal7551 2 ปีที่แล้ว

    what if we perform an in order traversal as it will be automatically sorted
    void helper(TreeNode* root,vector & v,int k){

    if(v.size()==k||root==NULL)
    return;
    helper(root->left,v,k);
    v.push_back(root->val);
    helper(root->right,v,k);
    }

    int kthSmallest(TreeNode* root, int k) {
    vector v;
    helper(root,v,k);
    return v[k-1];
    }
    the complexity is still O(min (k,n))
    wont that will be more efficient

    • @mdshaqlain3252
      @mdshaqlain3252 2 ปีที่แล้ว

      time complexity will be O(N), since we have to go to every node if we are storing in vector

  • @shashankojha3452
    @shashankojha3452 3 ปีที่แล้ว

    That makes sense

  • @purushottam108
    @purushottam108 5 หลายเดือนก่อน

    finally after this video, your face is in the video, video is booring without your face and newer version of you make thing more clear then older version of striver.

  • @NikhilGupta-zo5jh
    @NikhilGupta-zo5jh 2 ปีที่แล้ว

    understood

  • @adityaprakash1172
    @adityaprakash1172 ปีที่แล้ว

    I am getting runtime error in Leetcode everytime while doing through Morris Traversal
    int kthSmallest(TreeNode* root, int k) {
    if(root == NULL) return -1;
    int cnt=0;
    TreeNode* curr = root;
    TreeNode* temp;
    while(curr){
    if(curr -> left == NULL){
    temp = curr;
    cnt++;
    curr = curr -> right;
    }
    else{
    TreeNode* pred = curr -> left;
    while(pred -> right && pred -> right != curr)
    pred = pred -> right;
    if(pred -> right == NULL){
    pred -> right = curr;
    curr = curr -> left;
    }
    else{
    pred -> right = NULL;
    temp = curr;
    cnt++;
    curr = curr -> right;
    }
    }

    if(cnt == k){
    return temp -> val;
    }
    }

    return -1;
    }
    Can anyone correct it?

    • @zanies6288
      @zanies6288 ปีที่แล้ว

      class Solution {
      public:
      int kthSmallest(TreeNode* root, int k) {
      int count = 0;
      int ans;
      TreeNode* curr = root;

      while(curr){
      if(curr->left == NULL){
      count++;
      if(count == k){
      ans = curr->val;
      }

      curr = curr->right;
      }
      else{
      TreeNode* prev = curr->left;

      while(prev->right && prev->right != curr){
      prev = prev->right;
      }

      if(prev->right == NULL){
      prev->right = curr;
      curr = curr->left;
      }
      else{
      count++;
      prev->right = NULL;
      if(count == k){
      ans = curr->val;
      }
      curr = curr->right;
      }
      }
      }

      return ans;
      }
      };

    • @divyanshjain7999
      @divyanshjain7999 7 หลายเดือนก่อน

      @@zanies6288 then this is not O(K) it becomes O(N)

  • @anubhavverma7193
    @anubhavverma7193 3 หลายเดือนก่อน +1

    int inorderTraversal(TreeNode* root, int k) {
    TreeNode* curr = root;
    int cnt=0;
    while(curr)
    {
    if(curr->left==NULL)
    {
    cnt++;
    if(k==cnt) return curr->val;
    curr=curr->right;
    }
    else
    {
    TreeNode* prev = curr->left;
    while(prev->right && prev->right!=curr)
    {
    prev = prev->right;
    }
    if(prev->right==NULL)
    {
    prev->right=curr;
    curr=curr->left;
    }
    else
    {
    prev->right=NULL;
    cnt++;
    if(k==cnt) return curr->val;
    curr=curr->right;
    }
    }
    }
    return -1;
    }
    int kthSmallest(TreeNode* root, int k) {
    if(root==NULL) return -1;
    return inorderTraversal(root , k);
    }
    for this code im getting the following error
    AddressSanitizer:DEADLYSIGNAL
    =================================================================
    ==22==ERROR: AddressSanitizer: stack-overflow on address 0x7ffea2a00ff8 (pc 0x564fc93607d9 bp 0x7ffea2a01010 sp 0x7ffea2a01000 T0)
    #0 0x564fc93607d9 in __TreeNodeUtils__::freeTreeHelper(TreeNode*) (solution+0x1a87d9)
    #1 0x564fc9360800 in __TreeNodeUtils__::freeTreeHelper(TreeNode*) (solution+0x1a8800)
    #2 0x564fc9360800 in __TreeNodeUtils__::freeTreeHelper(TreeNode*) (solution+0x1a8800)
    #3 0x564fc93607dd in __TreeNodeUtils__::freeTreeHelper(TreeNode*) (solution+0x1a87dd)
    #4 0x564fc9360800 in __TreeNodeUtils__::freeTreeHelper(TreeNode*) (solution+0x1a8800)
    #5 0x564fc9360800 in __TreeNodeUtils__::freeTreeHelper(TreeNode*) (solution+0x1a8800)
    #6 0x564fc93607dd in __TreeNodeUtils__::freeTreeHelper(TreeNode*) (solution+0x1a87dd)

  • @shantipriya370
    @shantipriya370 11 หลายเดือนก่อน

    us..

  • @suvanshmahajan5902
    @suvanshmahajan5902 2 ปีที่แล้ว

    "us"

  • @ajayypalsingh
    @ajayypalsingh 2 ปีที่แล้ว

    💚

  • @preetikushwaha8734
    @preetikushwaha8734 3 ปีที่แล้ว

    Finally 🔥

  • @momilijaz271
    @momilijaz271 2 ปีที่แล้ว

    done!

  • @p38_amankuldeep75
    @p38_amankuldeep75 2 ปีที่แล้ว

    💝💙💝

  • @KaushikSharma-c3q
    @KaushikSharma-c3q ปีที่แล้ว

    .....................

  • @piyushacharya7696
    @piyushacharya7696 2 ปีที่แล้ว

    reach++

  • @SHASHANKRUSTAGII
    @SHASHANKRUSTAGII 3 ปีที่แล้ว

    im the 400 like

  • @Girish415
    @Girish415 3 ปีที่แล้ว

    Coolm

  • @JEAnandkumar
    @JEAnandkumar 2 ปีที่แล้ว +109

    One correction:
    k th largest element = (n-k+1)th smallest element

    • @parthsalat
      @parthsalat 2 ปีที่แล้ว +6

      Exactly! I was thinking about this

    • @ayushkushwaha171
      @ayushkushwaha171 ปีที่แล้ว

      correct!

    • @khushududeja2183
      @khushududeja2183 5 หลายเดือนก่อน

      right. i was thinking the same.

  • @sibiranganath
    @sibiranganath หลายเดือนก่อน

    Understood

  • @abhinanda7049
    @abhinanda7049 7 หลายเดือนก่อน

    understood