寻找BST中第k小的节点。
看了下,主流有两种解法。
1. 利用BST的特性:若节点n有i个左子结点,则其一定是第i+1小的节点。我们不妨加一个方法countNum(Node)来计算Node和其所有子节点的数量从而确定Node父节点的大小,通过比较判断第k个节点在左侧还是右侧,不断逼近。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int kthSmallest(TreeNode root, int k) {
int num = countNum(root.left);
if(k<=num)
{
return kthSmallest(root.left,k);
}
else if(k==num+1)
{
return root.val;
}
else
{
return kthSmallest(root.right,k-num-1);
}
}
static int countNum(TreeNode t)
{
if(t==null)
{
return 0;
}
return 1+countNum(t.left)+countNum(t.right);
}
}
时间为496 ms
2. 深搜
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
static int count,rt;
public int kthSmallest(TreeNode root, int k) {
count = k;
rt=0;
DP(root,k);
return rt;
}
static void DP(TreeNode n,int k)
{
if(n.left != null)
{
DP(n.left,k);
}
count--;
if(count==0)
{
rt = n.val;
return ;
}
if(n.right != null)
{
DP(n.right,k);
}
}
}
耗时
396 ms |