/**
* 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. poj 2116 Death to Binary? 模拟

    Death to Binary? Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 1707   Accepted: 529 D ...

  2. tp5定时器

    # 定时器 * * * * * cd /home/wwwroot/default/dexin/dragon && /usr/bin/php think order --option 1 ...

  3. eclipse导入redis的源码

    import--c/c++ Executable  选择编译后的so文件.这样就导入工程了. 可以在eclipse直接修改c代码,重新编译后就能看到效果了. 重新编译: 1:make clean 2: ...

  4. Angular中文api

    Angular中文api:http://docs.ngnice.com/api

  5. Codeforces 895C Square Subsets:状压dp【组合数结论】

    题目链接:http://codeforces.com/problemset/problem/895/C 题意: 给你n个数a[i].(n <= 10^5, 1 <= a[i] <= ...

  6. spring boot 基础篇 -- 定时任务

    在日常项目中,常常会碰到定时监控项目中某个业务的变化,下面是spring boot 集成的定时任务具体配置: @Component public class IndexWarningScheduled ...

  7. PHP用mysql_insert_id()函数获得刚插入数据或当前发布文章的ID

    向mysql 插入数据时,很多时候我们想知道刚刚插入数据的id,这对我们很有用.下面这篇文章就详细给大家介绍了利用mysql_insert_id()函数获得刚插入数据或当前发布文章的ID,有需要的朋友 ...

  8. 2018.8.10 programming bat based on python

    @echo off REM Current DevProg Version. Match the pip package version (x.y.z)SET currentversion=0.4.0 ...

  9. hdu 4445 Crazy Tank(物理过程枚举)

    遇到物理题,千万不要一味的当成物理题去想着推出一个最终结果来,这样ACM竞赛成了物理比赛,出题人就没水平了...往往只需要基础的物理分析,然后还是用算法去解决问题.这题n小于等于200,一看就估计是暴 ...

  10. Shell脚本备份Mongodb数据库

    目录 环境还原 环境创建 编写shell脚本 准备文件 创建shell脚本 执行shell脚本 进阶版 感谢 诚邀访问我的个人博客:我在马路边 更好的阅读体验点击查看原文:Shell脚本备份Mongo ...