[LeetCode-230]Kth Smallest Element in a BST

来源:互联网 发布:qt初学者 知乎 编辑:程序博客网 时间:2024/05/22 12:23
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?

Solution:

/** * 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 tree_size(TreeNode* root){        if (root){            return tree_size(root->left) + tree_size(root->right) + 1;        } else {            return 0;        }    }    int kthSmallest(TreeNode* root, int k) {        if (tree_size(root->left) + 1 == k) {            return root->val;        } else if (tree_size(root->left) + 1 > k) {            return kthSmallest(root->left, k);        } else {            return kthSmallest(root->right, k-(tree_size(root->left)+1));        }    }};
0 0