[Leetcode] Kth smallest Element in a BST

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.