题目描述
给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
public class Solution {
public int count = 0;
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot != null){ //中序遍历寻找第k个
TreeNode node = KthNode(pRoot.left,k);
if(node != null)
return node;
count ++;
if(count == k)
return pRoot;
node = KthNode(pRoot.right,k);
if(node != null)
return node;
}
return null;
}
}
本文介绍了一种在二叉搜索树中查找第K大结点的方法。通过中序遍历的方式,利用计数变量记录遍历过的结点数量,当计数等于K时返回当前结点。
185

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



