[leedcode 230] Kth Smallest Element in a BST
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?
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { /* 两种思路: 1.空间换时间 BST的特性是,如果按照中序排列,得到的递增序;所以可以使用一个stack进行中序遍历,直到找到第K个元素; 2. 树树的结点数 对于每个节点root,计算以它为根节点的左子树的节点数,计作S。 如果S+1==K,返回root->val; 如果S+1 > K,在root的左子树里面查找第K小元素; 如果S+1 > k ,在root的右子树里面查找第k-s-1小元素*/ public int kthSmallest(TreeNode root, int k) { /*Stack<TreeNode> stack=new Stack<TreeNode>(); while(!stack.isEmpty()||root!=null){ while(root!=null){ stack.push(root); root=root.left; } TreeNode temp=stack.pop(); k--; if(k==0){ return temp.val; } root=temp.right; } return 0;*/ if(root==null) return 0; int left=find(root.left); if(left+1==k) return root.val; if(left+1<k) return kthSmallest(root.right,k-left-1); else return kthSmallest(root.left,k); } public int find(TreeNode p){ if(p==null) return 0; return find(p.left)+find(p.right)+1; } }