二叉搜索树中第K小的元素

给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。

说明:
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。

示例 1:

输入: root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
   2
输出: 1

示例 2:

输入: root = [5,3,6,2,4,null,null,1], k = 3
       5
      / \
     3   6
    / \
   2   4
  /
 1
输出: 3

一个中序遍历的搜索,递归或者栈。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
void inorderSearch(struct TreeNode* root,int* count,int k,int* target)
{
    if(*count>k)
        return;
    if(root->left)
        inorderSearch(root->left,count,k,target);
    (*count)++;
    if(*count==k)
    {
        *target=root->val;
        return ;
    }
    if(root->right)
        inorderSearch(root->right,count,k,target);
        
}
int kthSmallest(struct TreeNode* root, int k) {
    int target=0;
    int count=0;
    inorderSearch(root,&count,k,&target);
    return target;
}

 

posted @ 2018-07-17 17:06  onlyandonly  阅读(198)  评论(0编辑  收藏  举报