题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。
样例
(5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
思路分析
方法一:递归法 二叉搜索树按照中序遍历的顺序 打印出来 即为升序排序 设置一计数器 进行中序排序 找到第k个 即可
方法二:非递归法 构造一个栈,思路同 中序遍历的非递归法
代码及结果
方法一:
int count = 0;
TreeNode ans;
TreeNode KthNode(TreeNode pRoot, int k){
helper(pRoot, k);
return ans;
}
public void helper(TreeNode node, int k){
if (node==null || count>k) {
return;
}
helper(node.left, k);
count++;
if (count == k) {
ans = node;
}
helper(node.right, k);
}
方法二:
TreeNode KthNode(TreeNode pRoot, int k){
if (pRoot == null) {
return null;
}
int count = 0;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode temp = null;
while (!stack.isEmpty() || pRoot!=null) {
while (pRoot != null) {
stack.push(pRoot);
pRoot = pRoot.left;
}
TreeNode node = stack.pop();
count++;
if (count == k) {
temp = node;
}
pRoot = node.right;
}
return temp;
}