LeetCode 230. Kth Smallest Element in a BST 动态演示

时间:2022-01-28 20:35:44

返回排序二叉树第K小的数

还是用先序遍历,记录index和K进行比较

class Solution {
public:
void helper(TreeNode* node, int& idx, int k, int& res){
if(res!=INT_MAX)
return; if(!node)
return; //a(node)
//lk("root",node)
//dsp helper(node->left, idx, k, res); if(idx==k){
res=node->val;
//dsp
}
++idx;
helper(node->right, idx, k, res);
} int kthSmallest(TreeNode* root, int k) {
int idx=;
int res=INT_MAX;
//ahd(root)
//a(res)
//a(k)
//a(idx)
helper(root, idx, k, res);
return res;
}
};

程序运行动态演示 http://simpledsp.com/FS/Html/lc230.html