您的位置:首页 > 其它

[leetcode]230. Kth Smallest Element in a BST

2017-04-04 21:13 274 查看
BST二叉搜索树,性质:每个节点的左孩子小于根节点,右孩子大于根节点

根据BST的性质,以及数组中第k大数的思想(QuickSelect分割思想),

先计算当前结点的左孩子节点的个数,与k比较

如果小于k-1(考虑当前节点),则第k大的数在右孩子节点

如果大于k-1,则第k大的数载左孩子节点

如果等于k-1,则返回当前结点的值

public int kthSmallest(TreeNode root, int k) {
int count = countNode(root.left);
if(count==k-1){
return root.val;
}else if(count<k-1){
return kthSmallest(root.right,k-1-count);
}else if(count>k-1){
return kthSmallest(root.left,k);
}
return -1;
}
public int countNode(TreeNode root){
if(root==null){
return 0;
}
return 1+countNode(root.left)+countNode(root.right);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: