[LeetCode from scratch] Kth Smallest Element in a BST

Source: Internet
Author: User

[LeetCode from scratch] Kth Smallest Element in a BST

Question:

 

Given a binary search tree, write a functionkthSmallestTo 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 wocould you optimize the kthSmallest routine?

Answer:

The beauty of programming has a similar question: Find the K large number in an array (unordered. Here is BST, which is already in order, which is more convenient.

 

If Left subtreeIf the number is greater than or equal to K, find the K number in the left subtree. If Left subtreeThe number is equal to the K-1, then the root node is the K; if Left subtreeIf the number is smaller than K, find the number (K-leftSum-1) in the right subtree (do not forget Root Node) How many nodes does the left subtree have? Another recursive program is required for calculation.

 

/** * 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 findNodeSum(TreeNode* root) {        if (root == NULL)       return 0;        return (findNodeSum(root->left) + findNodeSum(root->right) + 1);    }        int kthSmallest(TreeNode* root, int k) {        int leftSum = findNodeSum(root->left);        if (leftSum >= k)            return kthSmallest(root->left, k);        else if (leftSum == k - 1)  return root->val;        else        {            return kthSmallest(root->right,k - leftSum - 1);        }    }};
The question is not complete yet. What if BST is always modifying?

 

It is best to modify the tree node Structure and add an attribute: Total number of nodes in the left subtree. In this way, the search complexity is O (height)

 

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.