/**
* 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. Codeforces Round #273 (Div. 2) D. Red-Green Towers 背包dp

    D. Red-Green Towers time limit per test 2 seconds memory limit per test 256 megabytes input standard ...

  2. java collection接口源码

    package java.util; 02. 03./* 04.* 1.Collection接口是集合继承关系中的根接口(root interface),有些集合允许重复元素, 05.* 有些集合有序 ...

  3. C# WPF DataGrid 隔行变色及内容居中对齐

    C# WPF DataGrid 隔行变色及内容居中对齐. dqzww NET学习0     先看效果: 前台XAML代码: <!--引入样式文件--> <Window.Resourc ...

  4. shell获取ip地址

    Mac: $ ifconfig en0|awk -F"[ ]+" '/inet/{print $2}' fe80::a211:9bff:fe15:%en0 192.168.0.10 ...

  5. linux(ubuntu16.04)下安装和破解pycharm专业版

    我用的linux 版本是ubuntu,查看版本命令是: lsb_release -a 因为学习Python爬虫,pycharm是Python很好用的IDE,但是专业版需要付费,所以开始安装: 首先在官 ...

  6. Eclipse_插件_05_自动下载jar包源码插件

    一.Java Source Attacher 1.下载 官网:http://marketplace.eclipse.org/content/java-source-attacher#.U5RmTePp ...

  7. LeetCode OJ:Combination Sum III(组合之和III)

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

  8. js改变select的选中项不触发select的change事件

    // test var selectEl = document.querySelector('select') var buttonEl = document.querySelector('butto ...

  9. Phone numbers

    Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, ...

  10. python 编码拓展,小数据池,

    编码拓展: 1.在所有类型的编码中,编码的二进制互不识别, 2.在传输的过程中不能是万国码的二进制解码传输, 因此将unicode变为utf - 8或者变成gbk编码尤为重要; 利用encode编码为 ...