二叉搜索树的第k个节点
给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot==null||k<=0){
return null;
}
int count=0;
TreeNode node = pRoot;
TreeNode kthNode =null;
Stack<TreeNode> stack = new Stack();
while (node!=null||!stack.isEmpty()){
while (node !=null){
stack.push(node);
node = node.left;
}if(!stack.isEmpty()) {
node=stack.pop();
count++;
if(count==k){
kthNode=node;
return kthNode;
}
node=node.right;
}
}
return null;
}
}