面试题54.二叉搜索树的第k大节点
题目描述
给定一棵二叉搜索树,请找出其中第k大的节点。
题解
二叉搜索树的第k大节点,将二叉搜索树中序遍历得到从小到大的序列,鉴于长度不断改变,使用集合存储,从小到大的序列,要第k大,则返回倒数第k个数即可,代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int kthLargest(TreeNode root, int k) {
List<Integer> list = new ArrayList<>();
getList(root,list);
return list.get(list.size() - k);
}
//中序遍历二叉搜索树,将数存入集合中
private void getList(TreeNode root,List<Integer> list){
if(root == null) return;
if(root.left != null) getList(root.left,list);
list.add(root.val);
if(root.right != null) getList(root.right , list);
}
}
题解2
改进上面的代码,右根左遍历,到第k个结束,代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int ans = 0, count = 0;
public int kthLargest(TreeNode root, int k) {
getList(root, k);
return ans;
}
private void getList(TreeNode root, int k) {
if (root.right != null) getList(root.right, k);
if (++count == k) {
ans = root.val;
return;
}
if (root.left != null) getList(root.left, k);
}
}