Monday, August 7, 2017

[Leetcode] Kth Smallest Element in a BST, Solution

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note: 
You may assume k is always valid, 1 ? k ? BST's total elements.
Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

[Thoughts]
递归遍历二叉树,在遍历过程中算kth。


[Code]
1:    int kthSmallest(TreeNode* root, int k) {  
2:      int count = 0;  
3:        
4:      return kthSmallestImpl(root, count, k);  
5:        
6:    }  
7:      
8:    int kthSmallestImpl(TreeNode* root, int& count, int k) {  
9:      if(root == NULL) return -1;  
10:        
11:      int lr = kthSmallestImpl(root->left, count, k);  
12:      count++;  
13:      if(count == k) {  
14:        return root->val;  
15:      }  
16:        
17:      int rr = kthSmallestImpl(root->right, count, k);  
18:      return lr != -1 ? lr : rr;  
19:    }  

3 comments:

James David said...

Very Nice Post, I learned a lot through it. Thanks for posting.
digitizing for embroidery

JamesF Jones said...

Nice post I have learned a lot throughout this blog thanks for sharing keep it up. by cheap digitizing embroidery

ak said...

Looking for the best event management company in Dubai? Unique Angle is one of the top event management companies in Dubai, offering creative, customized, and professional event planning services. From corporate events to luxury weddings, exhibitions, and brand activations – we bring your vision to life with precision and style. Trust Unique Angle for seamless event execution across the UAE.

Top event management companies in Dubai