Title description
// 54. 二叉搜索树的第k大节点
// 力扣
// 给定一棵二叉搜索树,请找出其中第k大的节点。
// 牛客
// 给定一棵二叉搜索树,请找出其中的第k小的TreeNode结点。
answer
/
// 中序遍历的非递归方法
// 这题建议先做牛客,再做力扣
// 还记得BST的性质:左子结点比根节点小,根节点比右子结点小
// 且BST的中序遍历出来的元素是升序的。
// 牛客
// 牛客题目简单,找第k小的结点,直接中序遍历,中序遍历出来的元素就是
// 升序的,直接返回遍历的第k个结点。
// 我们创建一个count计数位,计数遍历的结点个数,数到第k个,直接返回结点。
// 运行时间:16ms,超过92.82%用Java提交的代码
// 占用内存:9872KB,超过11.21%用Java提交的代码
import java.util.Stack;
public class Solution {
public int count = 0;
TreeNode res;
TreeNode KthNode(TreeNode pRoot, int k) {
if (pRoot == null)
return null;
return inorder(pRoot, k);
}
// 中序遍历的非递归遍历
private TreeNode inorder(TreeNode root, int k) {
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
count++;
if (cur != null && count == k) {
res = cur;
return res;
}
cur = cur.right;
}
return null;
}
}
// 力扣
// 力扣的题目稍微难一点,需要找第k大的结点。就需要找到降序遍历结点的方法,
// 其实很简单,也是中序遍历,把中序遍历的 左-根-右,改成 右-根-左 即可。
// 其他部分跟牛客解法一模一样。
// 执行用时:1 ms, 在所有 Java 提交中击败了41.99%的用户
// 内存消耗:38.4 MB, 在所有 Java 提交中击败了41.12%的用户
class Solution {
public int count = 0;
TreeNode res;
public int kthLargest(TreeNode root, int k) {
if (root == null)
return -1;
return inorder(root, k);
}
private int inorder(TreeNode root, int k) {
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur);
cur = cur.right;
}
cur = stack.pop();
count++;
if (cur != null && count == k) {
res = cur;
return res.val;
}
cur = cur.left;
}
return -1;
}
}
// 中序遍历的递归方法
// 牛客
// 运行时间:17ms,超过87.35%用Java提交的代码
// 占用内存:9984KB,超过5.38%用Java提交的代码
public class Solution {
public int count = 0;
TreeNode res;
TreeNode KthNode(TreeNode pRoot, int k) {
if (pRoot == null)
return null;
inorder(pRoot, k);
return res;
}
// 中序遍历的非递归遍历
private void inorder(TreeNode root, int k) {
if (root == null)
return;
inorder(root.left, k);
count++;
if (count == k)
res = root;
inorder(root.right, k);
}
}
// 力扣
// 执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
// 内存消耗:38.2 MB, 在所有 Java 提交中击败了75.05%的用户
class Solution {
public int count = 0;
TreeNode res = null;
public int kthLargest(TreeNode root, int k) {
if (root == null)
return -1;
inorder(root, k);
return (res == null) ? -1 : res.val;
}
private void inorder(TreeNode root, int k) {
if (root == null)
return;
inorder(root.right, k);
count++;
if (count == k)
res = root;
inorder(root.left, k);
}
}