LeetCode-230. Kth Smallest Element in a BST (JAVA)二叉树第k小的数字
2017-04-29 10:36
363 查看
230. Kth Smallest Element in a BST
Given a binary search tree, write a functionkthSmallestto find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ? k ? BST's total elements.
BST中第k小的数字,中序遍历,没啥好说的。
private TreeNode temp;
private int counter;
public int kthSmallest(TreeNode root, int k) {
inorder(root, k);
return temp.val;
}
public void inorder(TreeNode node, int k) {
// perform in order tree traversal
if (node == null)
return; // base case
inorder(node.left, k);
if (++counter == k) {
temp = node;
return;
}
inorder(node.right, k);
}
迭代:
// k输入有效,中序遍历
public int kthSmallest(TreeNode root, int k) {
Stack<TreeNode> stk = new Stack<>();
while (root != null || !stk.isEmpty()) {
if (root != null) {
stk.push(root);
root = root.left;
} else {
root = stk.pop();
if (--k == 0)
return root.val;
root = root.right;
}
}
// 此题k输入合法,不会到达这里
return Integer.MIN_VALUE;
}
相关文章推荐
- [LeetCode] 230. Kth Smallest Element in a BST 二叉搜索树中的第K小的元素
- leetcode-java-230. Kth Smallest Element in a BST
- 【二叉树】BST第K小值【230. Kth Smallest Element in a BST】
- [leetcode 230]Kth Smallest Element in a BST----求二叉搜索树的第K小值
- [LeetCode]230. Kth Smallest Element in a BST
- LeetCode 230. Kth Smallest Element in a BST
- [leetcode-230]Kth Smallest Element in a BST(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
- 【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 (2 solutions)
- [leetcode] 230. Kth Smallest Element in a BST
- LeetCode 230. Kth Smallest Element in a BST
- [LeetCode] Kth Smallest Element in a BST 二叉搜索树中的第K小的元素
- LeetCode - 230. Kth Smallest Element in a BST