LeetCode题解:Kth Smallest Element in a BST
来源:互联网 发布:办公室新装修 知乎 编辑:程序博客网 时间:2024/06/06 03:50
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?
Hint:
Try to utilize the property of a BST.
What if you could modify the BST node’s structure?
The optimal runtime complexity is O(height of BST).
题意:给定二叉搜索树,找出第K小的数。假如二叉树经常会被修改,而且频繁需要查找第K小的数呢?
解题思路:DFS
代码:
/** * 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) { if(root == null){ return 0; } int leftNodeNums = countNodeNums(root.left); if(leftNodeNums == k - 1){ return root.val; }else if(leftNodeNums < k){ return kthSmallest(root.right, k - leftNodeNums - 1); }else{ return kthSmallest(root.left, k); } } private int countNodeNums(TreeNode root){ if(root == null){ return 0; } return 1 + countNodeNums(root.left) + countNodeNums(root.right); }}
0 0
- LeetCode题解:Kth Smallest Element in a BST
- LeetCode题解-230-Kth Smallest Element in a BST
- #leetcode#Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- Leetcode|Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- 【LeetCode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- leetcode: Kth Smallest Element in a BST
- Leetcode: Kth Smallest Element in a BST
- [LeetCode] Kth Smallest Element in a BST
- [LeetCode]Kth Smallest Element in a BST
- [Leetcode]Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- 从头开始安装Ubuntu,cuda,cudnn,caffe,tensorflow,ROS
- 简单问题
- 剑指Offer patitionArray
- 机器学习系列-------机器学习路线图(附资料)
- PE文件解析
- LeetCode题解:Kth Smallest Element in a BST
- hdu 1213 How Many Tables
- 利用SE16n 修改数据
- Pixhawk之前期准备
- spark , NoSuchMethodError: ConcurrentHashMap.keySet 和failed to connect to master的错
- 蓝桥杯 字符串转整数
- 二叉查找树
- Notepad++开发JavaScript运行时中文出现乱码的解决方法
- 文本类控件(EditView 的介绍)