题目:给定一棵二叉搜索树,请找出其中第K大的节点。
思路:按照剑指中的思路可知,对于二叉搜索树来说,中序遍历是递增排序的,我们只需要求出该二叉树的中序遍历,在找到第K个节点就可以了。
代码来源:https://blog.csdn.net/snow_7/article/details/51926574
代码:public TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot == null || k <= 0) //如果根节点为空或者给定的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;
}
下面这个是我自己写的代码:
import java.util.*;
public class Solution {
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot==null||k<=0){
return null;
}
Stack<TreeNode> s=new Stack<>();
while(!s.isEmpty()||pRoot!=null){
while(pRoot!=null){
s.push(pRoot);
pRoot=pRoot.left;
}
if(!s.isEmpty()){
TreeNode temp=s.pop();
pRoot=temp.right;
k--;
if(k==0){
return temp;
}
}
}
return null;
}
}