1、题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
2、解析
这题意思很明确,在一个二叉搜索树中寻找第k小的结点。首先要知道二叉搜索树的定义,根节点大于等于左孩子,根节点小于等于右孩子。
那这题可以把这个二叉搜索树中序遍历,然后再直接取出第k个节点。
3、代码
3.1、中序遍历
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.ArrayList;
public class Solution {
ArrayList<TreeNode> list = new ArrayList<>();
TreeNode KthNode(TreeNode pRoot, int k)
{
addNode(pRoot);
//尝试使用递归查找
if(k>=1 && list.size()>=k)
return list.get(k-1);
else
return null;
}
//对二叉树进行中序遍历
void addNode(TreeNode cur){
if(cur!=null){
addNode(cur.left);
list.add(cur);
addNode(cur.right);
}
}
}
注意返回第k-1是因为数组长度减1才是我们要的节点。
3.2、利用堆栈
import java.util.Stack;
public class Solution {
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot == null || k <= 0){
return null;
}
Stack<TreeNode> stack = new Stack<>(); //建立栈
TreeNode cur = pRoot;
//while 部分为中序遍历
while(!stack.isEmpty() || cur != null){
if(cur != null){
stack.push(cur); //当前节点不为null,应该寻找左儿子
cur = cur.left;
}else{
cur = stack.pop();//当前节点null则弹出栈内元素,相当于按顺序输出最小值。
if(--k == 0){ //计数器功能
return cur;
}
cur = cur.right;
}
}
return null;
}
}
这个方法还没看懂,再说吧。