LeetCode OJ 之 Kth Smallest Element in a BST(BST中的第k小元素)

来源:互联网 发布:免费java教程视频下载 编辑:程序博客网 时间:2024/06/07 01:01

题目:

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note: 
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

思路:

1、中序遍历中查找

2、遍历每个结点的左、右子树中的结点个数

代码1:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int kthSmallest(TreeNode* root, int k)     {        int result = 0;        helper(root ,k , result);        return result;    }    void helper(TreeNode * root , int &k , int &result)    {        if(root == NULL)            return;        helper(root->left ,k , result);        k--;//每遍历一次,k-1,由于中序遍历是按从小到大遍历,因此遍历到第k次时,得到的数据就是第k小        if(k == 0)        {            result = root->val;            return;        }        helper(root->right ,k , result);    }    };

代码2(非递归中序遍历):

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int kthSmallest(TreeNode* root, int k)     {        if(root == NULL)            return -1;        TreeNode *p = root;        stack<TreeNode *> s;        while(p || !s.empty())        {            if(p)            {                s.push(p);                p = p->left;            }            else            {                p = s.top();                s.pop();                k--;                if(k == 0)                    return p->val;                p = p->right;            }        }        return -1;    }};

代码3:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int kthSmallest(TreeNode* root, int k)     {        int leftCount = helper(root->left);        if(k == leftCount + 1)  //如果左子树中有k-1个结点,说明当前结点是第k小结点            return root->val;        if(k < leftCount + 1)   //如果左子树超过k个结点,则对左子树调用,注意此时k不用改变            return kthSmallest(root->left , k);        else            return kthSmallest(root->right , k - leftCount - 1);//调用右子树,此时k要变化    }    int helper(TreeNode * root)    {        if(root == NULL)            return 0;        return 1 + helper(root->left) + helper(root->right);    }    };


0 0