/**
* 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. python使用笔记

    修改文件模板,支持中文. File -> Settings -> Editor -> File and Code templates -> python Scropt 在里面加 ...

  2. redis 按空间范围查询点位

    GEORADIUS GEORADIUS key longitude latitude radius m|km|ft|mi [WITHCOORD] [WITHDIST] [WITHHASH] [ASC| ...

  3. linux学习-磁盘管理

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

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

  5. 本地的html服务

    本地的调试的时候, 我们服务器返回的cookie就会变的失效,因为你的本地服务器的域名不太对.

  6. 51nod 1267 二分

    http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1267 1267 4个数和为0 基准时间限制:1 秒 空间限制:13107 ...

  7. VMware设置NAT网络及 CentOS 7IP配置

    1.打开VMware,选择  编辑, 虚拟网络编辑器 2.默认情况下,VMware8为我们NAT所使用的网卡,选中VMnet8 3.此处设置我们的IP地址,这个随便指定,我这里设置成192.168.2 ...

  8. 【暂时解决】win10下安装VS2017 15.3版本 提示 未能安装包“Microsoft.NET.4.6.FullRedist.NonThreshold.Resources,version=4.6.81.9,language=zh-CN”。

    win10下安装VS2017 15.3版本的时候,出现以上错误日志提示,请问如何解决的哇? 这个问题,开始我以为是我的安装包所在的路径问题引起的,但是我将安装包移动到了磁盘根目录进行安装,依然出现这个 ...

  9. java web service 上传下载文件

    1.新建动态web工程youmeFileServer,新建包com,里面新建类FileProgress package com; import java.io.FileInputStream; imp ...

  10. storm 学习教程

    转自:http://blog.csdn.net/hrn1216/article/details/51538962 翻译太累了,再也不想去翻译了,真的太累了: 在这个教程中, 你将学到如何创建一个Sto ...