/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int KthSmallest(TreeNode root, int k)
{
int count = countNodes(root.left);
if (k <= count)
{
return KthSmallest(root.left, k);
}
else if (k > count + )
{
return KthSmallest(root.right, k - - count); // 1 is counted as current node
} return root.val;
} public int countNodes(TreeNode n)
{
if (n == null) return ; return + countNodes(n.left) + countNodes(n.right);
}
}

https://leetcode.com/problems/kth-smallest-element-in-a-bst/#/description

补充一个python的实现,使用二叉树的中序遍历:

 class Solution:
def __init__(self):
self.l = list() def inOrder(self,root):
if root != None:
self.inOrder(root.left)
self.l.append(root.val)
self.inOrder(root.right) def kthSmallest(self, root: TreeNode, k: int) -> int:
self.inOrder(root)
return self.l[k-]

leetcode230的更多相关文章

  1. [Swift]LeetCode230. 二叉搜索树中第K小的元素 | Kth Smallest Element in a BST

    Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not ...

  2. leetcode230. 二叉搜索树中第K小的元素

    题目链接: https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/ 题目: 给定一个二叉搜索树,编写一个函数 kthSmalle ...

  3. LeetCode 230. 二叉搜索树中第K小的元素(Kth Smallest Element in a BST)

    230. 二叉搜索树中第K小的元素 230. Kth Smallest Element in a BST 题目描述 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的 ...

随机推荐

  1. BZOJ 1941 kd-tree

    模板题 题意说的可能有点不清楚 一开始的点必须在给定的n个点里面 所以枚举点 然后ask最大和最小值 估价函数中 最大值的写法和最小值不同 全部取max 而最小值在估价时 如果在某个点管辖的空间里 就 ...

  2. CSDN_博客__WapPc

    CSDN 博客  手机上的网址 和 PC上的网址,对应关系: 1. 举个例子: 手机上的网址: http://m.blog.csdn.net/article/details?id=7910239 PC ...

  3. 0.00-050613_boot.s

    ! boot.s ! ! It then loads the system at 0x10000, using BIOS interrupts. Thereafter ! it disables al ...

  4. 被人遗忘的MAX_FILE_SIZE文件上传限制大小参数

    在文件上传中,我们经常会要求显 示用户上传文件大小,超过上传限制的文件就会不允许用户上传.虽然我们可以用程序去判断上传文件是否超过限制,但是其实我们的PHP程序是无法判断用户本 地文件大小的.所以等到 ...

  5. 在Android中使用实时调度(real-time)

    Linux的线程调度策略中有FIFO和RT的实时调度方法,但是在Android中做了限制,普通用户不能修改线程的调度算法为FIFO和RT,必须ROOT用户才能更改.但问题是程序是以普通用户启动和运行的 ...

  6. LeetCode OJ:Flatten Binary Tree to Linked List(捋平二叉树)

    Given a binary tree, flatten it to a linked list in-place. For example,Given 1 / \ 2 5 / \ \ 3 4 6 T ...

  7. 条款42:了解typename的双重含义

    typename在很多种情况下与class是完全相同的,例如下面的使用: templame<typename T> ...... template<class T> ..... ...

  8. Mac 下 Mosquitto 安装和配置 (Mosquitto为开源的mqtt服务器)

    官网:http://mosquitto.org/download/ 官网的介绍简单明了 Mac 下一个命令“brew install mosquitto” 安装成功了,还学会了brew 安装目录:/u ...

  9. nyoj-1132-promise me a medal(求线段交点)

    题目链接 /* Name:nyoj-1132-promise me a medal Copyright: Author: Date: 2018/4/26 20:26:22 Description: 向 ...

  10. CodeForces - 688C:NP-Hard Problem (二分图&带权并查集)

    Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex c ...