题目:
给定一棵二叉搜索树,请找出其中第 k 大的节点的值。

限制:
1 ≤ k ≤ 二叉搜索树元素个数
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题过程①:
中序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> list = new LinkedList<>();
public int kthLargest(TreeNode root, int k) {
PreOrder(root,k);
return list.get(list.size()-k);
}
private void PreOrder(TreeNode root,int k){
if(root==null) return;
PreOrder(root.left, k);
list.add(root.val);
PreOrder(root.right, k);
}
}
执行结果①:

更高级的版本
解题过程②:
中序遍历,先右,再中,后左。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int count=0, ans=0;
public int kthLargest(TreeNode root, int k) {
InOrder(root, k);
return ans;
}
private void InOrder(TreeNode root,int k){
if(root==null) return;
// 先右
InOrder(root.right, k);
// 再中
if(++count==k){
ans = root.val;
return;
}
// 后左
InOrder(root.left, k);
}
}
执行结果②:

305

被折叠的 条评论
为什么被折叠?



