注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注
题目描述
给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int index = 0; //计数器
public TreeNode KthNode(TreeNode root, int k) {
//思路:二叉搜索树按照中序遍历的顺序打印出来正好就是排序好的顺序。
//所以,按照中序遍历顺序找到第k个结点就是结果。
if (root != null) { //中序遍历寻找第k个
TreeNode treeNode = KthNode(root.left, k);
if (treeNode != null)
return treeNode;
index++;
if (index == k)
return root;
treeNode = KthNode(root.right, k);
if (treeNode != null)
return treeNode;
}
return null;
}
}