?LeetCode刷題實(shí)戰(zhàn)230:二叉搜索樹(shù)中第K小的元素
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);
}
}
LeetCode1-220題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)221:最大正方形
LeetCode刷題實(shí)戰(zhàn)222:完全二叉樹(shù)的節(jié)點(diǎn)個(gè)數(shù)
LeetCode刷題實(shí)戰(zhàn)223:矩形面積
LeetCode刷題實(shí)戰(zhàn)224:基本計(jì)算器
LeetCode刷題實(shí)戰(zhàn)225:用隊(duì)列實(shí)現(xiàn)棧
LeetCode刷題實(shí)戰(zhàn)226:翻轉(zhuǎn)二叉樹(shù)
LeetCode刷題實(shí)戰(zhàn)227:基本計(jì)算器 II
LeetCode刷題實(shí)戰(zhàn)228:匯總區(qū)間
LeetCode刷題實(shí)戰(zhàn)229:求眾數(shù) II
