思路:
根据二叉搜索树的特点来解决,非空二叉搜索树是左子树上的所有节点比根节点小,右子树上的所有节点比根节点大,其左右子树同样遵循这个规则。
所以二叉搜索树的中序遍历结果,就是一个按照从大到小的顺序排序的序列,访问第K个节点时就终止程序即可。
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot == null || k <= 0)
return null;
TreeNode current = pRoot;
TreeNode kNode = null;//用来保存第K个节点
int count = 0;
LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
//中序遍历二叉搜索树
while(!stack.isEmpty() || current != null)
{
while(current!=null)
{
stack.push(current);
current = current.left;
}
if(!stack.isEmpty())
{
current = stack.pop();//每出栈一个节点让count++;对比count和K的值,第k个节点时跳出循环返回节点,
count++;
if(count == k)
{
kNode = current;
break;
}
current = current.right;
}
}
return kNode;
}