思想:左序搜索,在遍历的时候,用一个记录变量记录已经确定的点,因为小的点总是先访问到,每确定一个节点减去1。知道为零时候则是最k小的
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
public int kthSmallest(TreeNode root, int k) {
int record[]=new int[1];
record[0]=k;
return DFS(root, record).val;
}
public TreeNode DFS(TreeNode root,int record[])
{
if(record[0]==0)
{
return root;
}
TreeNode temp=null;
if(root.left!=null)
{
temp=DFS(root.left, record);
if(temp!=null)
{
return temp;
}
}
record[0]--;
if(record[0]==0)
{
return root;
}
if(root.right!=null)
{
temp=DFS(root.right, record);
if(temp!=null)
{
return temp;
}
}
if(record[0]==0)
{
return root;
}
return null;
}
}
本文介绍了一种在二叉搜索树中查找第K小元素的方法。通过递归地进行左序搜索,每访问一个节点就更新计数器,直至找到目标节点。
534

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



