给定一棵二叉搜索树,请找出其中第k大的节点。
思路:中序遍历
递归解法:
class Solution {
public int kthLargest(TreeNode root, int k) {
List<Integer> res=new ArrayList<Integer>();
inorder(root,res);
return res.get(res.size()-k);
}
public void inorder(TreeNode root, List<Integer> res){
if(root==null)
return;
inorder(root.left,res);
res.add(root.val);
inorder(root.right,res);
}
}
不需要额外空间,倒着中序遍历:
class Solution {
int k,res;
public int kthLargest(TreeNode root, int k) {
this.k=k;
res=0;
inorder(root);
return res;
}
public void inorder(TreeNode root){
if(root==null)
return;
inorder(root.right);
k--;
if(k==0){
res=root.val;
return;
}
inorder(root.left);
}
}
本文介绍了一种寻找二叉搜索树中第K大节点的方法。提供了两种递归解法:一种使用中序遍历将节点值存入列表再返回目标值;另一种通过倒序中序遍历直接找到目标节点而无需额外空间。
234

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



