Kth Smallest Element in a BST
Total Accepted: 28176 Total Submissions: 82688 Difficulty: Medium
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?
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void inorder(TreeNode* root, int &k,int &val){ if(!root) return; inorder(root->left,k,val); if(--k == 0){ val = root->val; return; } inorder(root->right,k,val); } int kthSmallest(TreeNode* root, int k) { int res = 0; inorder(root,k,res); return res; } };
写者:zengzy
出处: http://www.cnblogs.com/zengzy
标题有【转】字样的文章从别的地方转过来的,否则为个人学习笔记
 
                    
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号