本文主要是介绍leetcode No230. Kth Smallest Element in a BST,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Question:
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?
Algorithm:
Accepted Code:
/*** 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:int kthSmallest(TreeNode* root, int k) {return helper(root,k);}int helper(TreeNode* root, int &k){if(root==NULL)return -1;if(root->left){int temp=helper(root->left,k);if(temp!=-1)return temp;}if(k==1)return root->val;k--;return helper(root->right,k);}
};
这篇关于leetcode No230. Kth Smallest Element in a BST的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!