[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);
}
根据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);
}
相关文章推荐
- 【Leetcode】:230. Kth Smallest Element in a BST 问题 in JAVA
- [LeetCode]230. Kth Smallest Element in a BST
- Leetcode 230. Kth Smallest Element in a BST
- 【LeetCode】230. Kth Smallest Element in a BST (2 solutions)
- LeetCode 230. Kth Smallest Element in a BST
- [LeetCode]230. Kth Smallest Element in a BST
- leetcode-230. Kth Smallest Element in a BST
- 【leetcode】230. Kth Smallest Element in a BST
- leetcode-java-230. Kth Smallest Element in a BST
- 【leetcode】230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST LeetCode
- LeetCode 230. Kth Smallest Element in a BST
- [leetcode] 230. Kth Smallest Element in a BST 解题报告
- Leetcode 230. Kth Smallest Element in a BST (Medium) (cpp)
- LeetCode 230. Kth Smallest Element in a BST 解题报告
- LeetCode 230. Kth Smallest Element in a BST
- leetcode 230. Kth Smallest Element in a BST
- LeetCode *** 230. Kth Smallest Element in a BST
- [LeetCode] 230. Kth Smallest Element in a BST 解题思路
- [leetcode] 230. Kth Smallest Element in a BST