LeetCode刷题实战230:二叉搜索树中第K小的元素
程序IT圈
共 3281字,需浏览 7分钟
·
2021-04-06 11:32
Given the root of a binary search tree, and an integer k, return the kth (1-indexed) smallest element in the tree.
示例
解题
中序遍历方法
class Solution {
List<Integer> list = new ArrayList();
public void dfs(TreeNode root){
if(root == null)
return ;
dfs(root.left);
list.add(root.val);
dfs(root.right);
}
public int kthSmallest(TreeNode root, int k) {
dfs(root);
for(int i=0;i<list.size();i++){
if(i == k-1)
return list.get(i);
}
return -1;
}
}
class Solution {
public int count(TreeNode root){
if(root == null)
return 0;
return 1 + count(root.left) + count(root.right);
}
public int kthSmallest(TreeNode root, int k) {
int num = count(root.left);
if(num == k-1)
return root.val;
if(num > k-1)
return kthSmallest(root.left,k);
return kthSmallest(root.right,k - num-1);
}
}
评论