面試題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);
}
}