Leetcode 230:kth Smallest Element in a BST

Source: Internet
Author: User

Kth smallest Element in a BSTTotal Accepted: 3655 Total Submissions: 12149

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

Ideas

Recursion and non-recursion can be used. Here I used a non-recursive approach, similar to binary tree iterator. By the way, I looked at the recursive method on the Internet, the time complexity is very high, each time to calculate the tree size. Feeling even recursion, should also be able to optimize.

follow up is interesting to keep some extra information in the node: the size of the Zuozi. It is also necessary to maintain the size of the left subtree while inserting deletes. When looking again, you can use two points. Time Complexity of O (h)

[CODE]

/** * Definition for a binary tree node.  * public class TreeNode {*     int val, *     TreeNode left, *     TreeNode right; *     TreeNode (int x) {val = x;} *} */public class Solution {public    int kthsmallest (TreeNode root, int k) {        stack<treenode> Stack = new stack& Lt;> ();        TreeNode n = root;        while (n.left!=null) {            stack.push (n);            n = n.left;         }                while (k>0 && (n!=null | |!stack.isempty ())) {            if (n==null) {                n = stack.pop ();                if (--k==0) return n.val;                n = n.right;            } else {                stack.push (n);                n = n.left;            }        }        return n.val;}    }


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode 230: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.