Kth smallest Element in a BST
Given A binary search tree, write a function to kthSmallest
find the k-th smallest element in it.
Note:
You may assume k are always valid, 1≤k≤bst's total elements.
Follow up:
What if the BST are modified (Insert/delete operations) often and you need to find the kth smallest frequently? How would optimize the Kthsmallest routine?
Problem Solving Ideas:
This question seeks to find the number of the K-large of the tree species in two points. The binary search tree has one characteristic, each node is larger than all nodes of the left child tree, and is less than all nodes that have children's trees.
Therefore, it is possible to scan the binary search tree using the method of middle order traversal, and stop scanning when the number of K is scanned.
/** * 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) { int count = 0; int result = 0; Inorder (Root, K, count, result); return result; } void Inorder (treenode* root, int k, int& count, int& result) { if (Root==null | | count>=k) { return;< c13/>} inorder (Root->left, K, count, result); count++; if (count==k) { result=root->val; } Inorder (Root->right, K, count, result); }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode] Kth smallest Element in a BST