62.二叉搜索树的第k个结点
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
二叉搜索树按照中序遍历的顺序打印出来正好就是排序好的顺序。所以,按照中序遍历顺序找到第k个结点就是结果。
public class Solution {
int index=0;//计数器
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot!=null){
TreeNode leftnode=KthNode(pRoot.left,k);
if(leftnode !=null) // 左子树中找到符合要求的节点返回
return leftnode;
index++; // 从最左节点开始, index+1
if(index==k)
//此时找到对应节点,但是递归并没有结束,所以需要将结果逐层返回,所以return node。
return pRoot;
TreeNode rightnode=KthNode(pRoot.right,k);
if(rightnode!=null)
return rightnode;//左子树中没有找到,在右子树找到了符合要求的节点返回
}
return null;
}
}
方法2:
import java.util.*;
public class Solution {
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot==null||k==0)
return null;
int count=0;
Stack<TreeNode> stack=new Stack<>();
while(pRoot!=null||!stack.isEmpty()){
while(pRoot!=null){
stack.push(pRoot);
pRoot=pRoot.left;
}
pRoot=stack.pop();
count++;
if(count==k) return pRoot;
pRoot=pRoot.right;
}
return null;
}
}