leetcode : Kth Smallest Element in a BST
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?
题目简单,找BST树中第kth小的节点,直接中序遍历就可以。
AC代码:
/** * 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 kth = k, ret = 0; return midV(root, kth, ret); } int midV(TreeNode* root, int &k, int &ret) { if(root->left) { midV(root->left, k, ret); } --k; if(k == 0) { ret = root->val; } if(root->right) { midV(root->right, k, ret); } return ret; } };
因为在遍历的过程中需要保存已经遍历到第几个节点了,一开始想用static变量保存这个值,代码是这样的:
int kthSmallest(TreeNode* root, int k) { static int ret; static int kk = k; if(root->left) { kthSmallest(root->left, k); } --kk; if(kk == 0) { ret = root->val; } if(root->right) { kthSmallest(root->right, k); } return ret; }
c++中局部静态变量是在 (函数调用期间) 第一次遇到 定义语句时进行初始化,是运行时开销,如果这个函数一直没调用,就不会初始化。而且只会初始化一次。
所以上面代码中kk的初始值就是第一次调用该函数时的k值,不管后面再来几次,初始值都不会变了。所以上面的写法从第二组测试用例开始,kk的值就一直是负的了,并且越来越小,由于kk不会为再次变0, ret的值也不会被改变。。。所以妥妥的会出错。
另外由于这种局部静态变量是存在静态区,并且声明周期是从被初始化开始一直活到程序结束,所以弄个指针指向这类局部静态变量,然后利用这个指针在随便什么地方都能改变他的值,但是这种方法感觉容易出岔子。。。。在一个随便什么乱七八糟的地方拿个指针就能瞎改别人的局部静态变量还是很不礼貌的行为的- -!
浙公网安备 33010602011771号