[Leetcode] Kth smallest Element in a BST

Source: Internet
Author: User

Given A binary search tree, write a function to kthSmallest find the kth 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?

Hint:try to utilize the property of a BST.

This question is similar to the previous next () method, but there is one more K value here.

Questions and hints we need to use BTS's definition to follow the sequence: Left < root < right

So at the very beginning we first add all the rightmost TreeNode, not just the right thing, the node on the left is equally important.

Example: Stack.pop () after the present minimum value (only store the left TreeNode case), then pop () must be the second small? Certainly not, if the minimum node node.right!=null, it is clear that the value of node.right is smaller than the second-to-last node. (It's a little confusing, but it's a drawing comprehension.) =

So we then pop () out of the current minimum value, before the second pop () should immediately detect its node.right and put these values in the order store into the stack, and then the second run with the help of if statement.

The code is as follows. ~

public class Solution {public    int kthsmallest (TreeNode root, int k) {    stack<treenode> Stack = new stack< Treenode> ();    TreeNode p = root;    int result = 0;     while (!stack.isempty () | | p!=null) {        if (p!=null) {            stack.push (p);            p = p.left;        } else{            TreeNode temp = Stack.pop ();            k--;            if (k==0) {                result = Temp.val;            }            p = temp.right;        }    }     return result;}}

[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.