leetcode -- 230. Kth Smallest Element in a BST 【遍历 + 计数】
2017-02-11 01:03
411 查看
题目
Given a binary search tree, write a functionkthSmallestto find thekth 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?
题意
给定一个二叉搜索树,通过一个方法kthSmalllest 来知道第k 小的元素。(注意题目中的假设)分析及代码
方法1(全局计数器):【二叉搜索树的定义及特点】
二叉排序树或者是一棵空树,或者是具有下列性质的二叉树:
(1)若左子树不空,则左子树上所有结点的值均小于或等于它的根结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值;
(3)左、右子树也分别为二叉排序树;
【特点的运用】从小到大排列 ---> 中序遍历 ;从大到小排列
--> 中序遍历 + 栈(或者以右子树开始,进行中序遍历)
【参数分析】观察可知,方法的参数有两个,其中一个用来表示TreeNode(提供遍历的必要),k 用来说明限制,也告诉了我们的目标。
【返回值】最终的结果。我们需要在遍历达到目标的时候,不断从调用层次深处到顶层传递。(可能在调用底层某个点就已经达到目标了,返回时需保持)
【全局计数器】计数,&& count 与 k构成限制条件。
public class KthSmallest { int count = 0; public int kthSmallest(TreeNode root, int k) { TreeNode tgt = findTreeNode(root, k); return tgt.val; } public TreeNode findTreeNode(TreeNode root,int k){ if(root == null) return null; TreeNode left = findTreeNode(root.left, k); if(count == k) return left; if(++count == k) return root; return findTreeNode(root.right, k); } }
反例:
下面程序也正确,只不过有大量重复操作。(体现在countNodes处)(原程序地址)
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); // 1 is counted as current node
}
return root.val;
}
public int countNodes(TreeNode n) {
if (n == null) return 0;
return 1 + countNodes(n.left) + countNodes(n.right);
}
相关文章推荐
- 【Leetcode】:230. Kth Smallest Element in a BST 问题 in JAVA
- LeetCode 230. Kth Smallest Element in a BST
- leetcode-230. Kth Smallest Element in a BST
- 【LeetCode】230. Kth Smallest Element in a BST (2 solutions)
- [LeetCode] 230. Kth Smallest Element in a BST 解题思路
- [LeetCode]230. Kth Smallest Element in a BST
- [LEETCODE]230. Kth Smallest Element in a BST
- [leetcode] 230. Kth Smallest Element in a BST
- [leetcode] 230. Kth Smallest Element in a BST
- 【leetcode】230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST LeetCode
- LeetCode 230. Kth Smallest Element in a BST
- Leetcode 230. Kth Smallest Element in a BST
- Leetcode 230. Kth Smallest Element in a BST (Medium) (cpp)
- LeetCode 230. Kth Smallest Element in a BST 解题报告
- [LeetCode]230. Kth Smallest Element in a BST
- leetcode 230. Kth Smallest Element in a BST
- [leetcode] 230. Kth Smallest Element in a BST 解题报告
- LeetCode 230. Kth Smallest Element in a BST
- LeetCode - 230. Kth Smallest Element in a BST