题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
看到二叉搜索树,想到用中序遍历。
class Solution {
public:
int count = 0;
TreeNode* KthNode(TreeNode* pRoot, int k)
{
if(pRoot == NULL) return NULL;
KthNode(pRoot->left, k);
count++;
if(count == k)
return pRoot;
KthNode(pRoot->right, k);
return NULL;
}
};
修改,仍然不通过。
class Solution {
public:
int count = 0;
TreeNode* KthNode(TreeNode* pRoot, int k)
{
if(pRoot != NULL)
{
KthNode(pRoot->left, k);
count++;
if(count == k)
return pRoot;
KthNode(pRoot->right, k);
}
return NULL;
}
};
正确写法
class Solution {
public:
int count = 0;
TreeNode* KthNode(TreeNode* pRoot, int k)
{
if(pRoot != NULL)
{
TreeNode* node = KthNode(pRoot->left, k);
if(node != NULL)
return node;
count++;
if(count == k)
return pRoot;
node = KthNode(pRoot->right, k);
if(node != NULL)
return node;
}
return NULL;
}
};
递归,if(node != NULL)表明在子树里已经找到第k小的节点,直接返回。为NULL说明在子树没有找到,继续找。