leetcode230
/**
* 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的更多相关文章
- [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 ...
- leetcode230. 二叉搜索树中第K小的元素
题目链接: https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/ 题目: 给定一个二叉搜索树,编写一个函数 kthSmalle ...
- LeetCode 230. 二叉搜索树中第K小的元素(Kth Smallest Element in a BST)
230. 二叉搜索树中第K小的元素 230. Kth Smallest Element in a BST 题目描述 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的 ...
随机推荐
- Jboss remote getshell (JMXInvokerServlet) vc版
#include "stdafx.h" #include <Windows.h> #include <stdio.h> #include <winht ...
- OpenStack日志搜集分析之ELK
ELK 安装配置简单,用于管理 OpenStack 日志时需注意两点: Logstash 配置文件的编写 Elasticsearch 日志存储空间的容量规划 另外推荐 ELKstack 中文指南. E ...
- python中的变量与对象
一. 什么是变量 变量就是以前学习的数学中常见的等式x = 3(x是变量,3是变量值),在编程中,变量不仅可以是数学,还可以是任意数据类型 二. 变量的命名规则 变量名必须是英文大小写.数字和_的组合 ...
- 2016ACM/ICPC亚洲区沈阳站
emm,a出3题,补了两题 A,B水题 #include<bits/stdc++.h> #define fi first #define se second #define mp make ...
- linux查看网卡速度
ethtool eth0 会包含速度模式等各项属性信息 lspci|grep -i ether 可以查看硬件设备具体型号,会包含硬件厂商及信息 dmesg |grep -i eth 会显示系统 ...
- NSObject头文件解析 / 消息机制 / Runtime解读 (二)
本章接着NSObject头文件解析 / 消息机制 / Runtime解读(一)写 给类添加属性: BOOL class_addProperty(Class cls, const char *name, ...
- Tomcat 多端口访问多应用设置
目的 配置Tomcat,使用多端口访问不同应用 步骤 测试Tomcat版本为apache-tomcat-8.0.5,理论上支持7.0之上的版本 找到tomcat的主目录,打开conf文件夹,找到并打开 ...
- jstat 简介(2)
jstat命令可以查看堆内存各部分的使用量,以及加载类的数量.命令的格式如下: jstat [-命令选项] [vmid] [间隔时间/毫秒] [查询次数] 注意:使用的jdk版本是jdk8. 类加载统 ...
- UnityGUI扩展实例:图片挖洞效果 Mask的反向实现
转载自 https://www.taidous.com/forum.php?mod=viewthread&fid=211&tid=55259 我想大家在用uGUI做界面时,可能经常会碰 ...
- nyoj-115-城市平乱(dijkstra算法)
题目链接 /* Name:nyoj-115-城市平乱 Copyright: Author: Date: 2018/4/25 17:28:06 Description: dijkstra模板题 枚举从 ...