230. Kth Smallest Element in a BST(Java)
来源:互联网 发布:女士皮鞋品牌 知乎 编辑:程序博客网 时间:2024/06/10 00:25
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ? k ? BST’s total elements.
Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * 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 + 1) { return kthSmallest(root.right, k - 1 - count); } return root.val; } private int countNodes(TreeNode node) { if (node == null) return 0; return 1 + countNodes(node.left) + countNodes(node.right); } }
阅读全文
0 0
- (java) Kth Smallest Element in a BST
- 230.Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- STM32写内部FLASH
- 前端开发中的字符编码 xss
- 如何在C++中调用C程序?
- 设计模式-模板方法模式
- 浅析C++中的this指针
- 230. Kth Smallest Element in a BST(Java)
- 进程间通信之消息队列
- [笔记]生成学习算法·GDA·NB
- PID控制算法+倒立摆控制应用
- Ubuntu + Windows 10 安装 rEFInd
- JdbcTemplate的保存和查询方法
- 个性化vim配置
- 浅谈JS中的call、apply和bind
- 51nod 1284 2 3 5 7的倍数 容斥原理