LeetCode[230] Kth Smallest Element in a BST

来源:互联网 发布:多用户建站cms系统 编辑:程序博客网 时间:2024/05/22 09:54

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?

利用中序遍历的思想,用一个变量count记录遍历的节点个数,注意不要用static,因为如果 class A 有一个static变量x,  执行 A a;  A b;  时,x只会被初始化一次,b的x得不到想要的初值,而测试用例通常有好多个

/** * 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 count;int kthSmallest(TreeNode* root, int k) {int result = 0;if (root->left != NULL && count < k)result = kthSmallest(root->left, k);count++;if (count == k)result = root->val;if (root->right != NULL && count < k)result = kthSmallest(root->right, k);return result;}Solution(): count(0) { };};

0 0
原创粉丝点击