leetcode oj java 230. Kth Smallest Element in a BST
来源:互联网 发布:8051单片机引脚映射 编辑:程序博客网 时间:2024/04/30 00:34
一、问题描述:
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.
二。1、解决思路:
由于BST的左孩子节点的值都小于父节点,右孩子节点的值都大于父节点的特性,我们可以递归的去寻找K小的元素。
假设左子树的长度是length
如果 length + 1 = k 那么刚好是根节点的值
如果 length + 1 > k 那么结果在左子树中,还是寻找第k个。
如果 length + 1 < k 那么结果在右子树中,此时已经排除了左边的length+1 个,需要寻找k-(length+1)个。
附代码:
public static int kthSmallest(TreeNode root, int k) { if (root == null) { return 0; } int leftSize = count(root.left); if (k == leftSize + 1) { return root.val; } else if (k < leftSize + 1) { return kthSmallest(root.left, k); } else { return kthSmallest(root.right, k - leftSize - 1); } } public static int count(TreeNode root) { if (root == null) { return 0; } return 1 + count(root.left) + count(root.right); }
解决思路二:
中序遍历树,把结果存入list中,一旦list的长度大于K的时候就返回。然后取list的第k-1个值即可。
代码:
public static int kthSmallest(TreeNode root, int k) { List<Integer> re = new ArrayList<Integer>(); bianli(root, re, k); return re.get(k - 1); } public static List<Integer> bianli(TreeNode root, List<Integer> re, int k) { if (root == null || re.size() > k) { return re; } bianli(root.left, re, k); re.add(root.val); bianli(root.right, re, k); return re; }
0 0
- leetcode oj java 230. Kth Smallest Element in a BST
- <LeetCode OJ> 230. Kth Smallest Element in a BST
- leetcode-java-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
- 对于长期学习方式的一点看法
- C# 通过URL获取图片并显示在PictureBox上的方法
- “error LNK2019: 无法解析的外部符号”的几种可能原因
- C# 中,(int),Int32.Parse() 和 Convert.toInt32() 三种方法有何区别
- Spark SQL saveMode 方式
- leetcode oj java 230. Kth Smallest Element in a BST
- 不带缓冲的文件I/O操作
- Tomcat启动失败-提示Server Tomcat v7.0 Server at localhost failed to start.
- 重构项目中犯的一些低级错误
- cocos-Lua table积累
- python 遍历文件目录并修改包含某字符串的文件名字
- PHP处理excel文件 包括处理excel数据上传到数据库以及从数据库下载数据到excel
- my Linux 命令学习笔记
- 协同过滤算法