题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。
经典题
首先要确定二叉搜索树的特点
即 左子树比根树小 右子树比 根大
那么一个二叉搜索树的中序遍历就是从小到大排列
选取一个集合存储这些数据
即可得到顺序了
/*
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 {
public ArrayList<TreeNode> arr=new ArrayList<>();
TreeNode KthNode(TreeNode pRoot, int k)
{
midOrder(pRoot);
if (k>=1&&arr.size()>=k){
return arr.get(k-1);
}
return null;
}
public void midOrder(TreeNode root){
if (root!=null){
midOrder(root.left);
System.out.println(root.val);
arr.add(root);
midOrder(root.right);
}
}
}
博客围绕在二叉搜索树中找出第k小的结点这一问题展开。指出二叉搜索树左子树比根小、右子树比根大,其特点决定中序遍历是从小到大排列,可通过选取集合存储数据来确定顺序。
584

被折叠的 条评论
为什么被折叠?



