Given a binary search tree, write a function kthSmallest to 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 would you optimize the kthSmallest routine?
Try to utilize the property of a BST.
What if you could modify the BST node’s structure?
The optimal runtime complexity is O(height of BST).
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */publicclassSolution{// 必须要有两个global 变量intret;intcount;publicintkthSmallest(TreeNoderoot,intk){ret=0;count=k;inorder(root);returnret;}publicvoidinorder(TreeNoderoot){if(root.left!=null)inorder(root.left);count--;if(count==0){ret=root.val;return;}if(root.right!=null)inorder(root.right);}}
Mantain a stack to record the left subtree of current node.
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = NoneclassSolution(object):defkthSmallest(self,root,k):""" :type root: TreeNode :type k: int :rtype: int """stack=[]# push the most left nodesnode=rootwhilenode:stack.append(node)node=node.leftwhilestackandk>0:node=stack.pop()k=k-1# push the left subtree of the node.rightrightChild=node.rightwhilerightChild:stack.append(rightChild)rightChild=rightChild.leftreturnnode.val