题目
给定一棵二叉搜索树,请找出其中第k大的节点。
限制:
1 ≤ k ≤ 二叉搜索树元素个数
代码
class Solution {
public int kthLargest(TreeNode root, int k) {
Stack <TreeNode> stack = new Stack<>();
List<Integer> list = new ArrayList<>();
int count=0;
int ans=0;
// 将所有的数字按照中序遍历进行
while(root!=null || !stack.isEmpty())
{
while(root!=null)
{
stack.push(root);
root=root.left;
}
root=stack.pop();
list.add(root.val);
root=root.right;
}
int size=list.size();
// 遍历列表,获得该数值
for(int i=size-1;i>=0;--i)
{
++count;
if(count==k)
{
ans=list.get(i);
break;
}
}
return ans;
}
}