博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Kth Smallest Element in a BST
阅读量:7196 次
发布时间:2019-06-29

本文共 1049 字,大约阅读时间需要 3 分钟。

 

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?

 

/** * 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:    void _get_in_order_list(TreeNode* root, vector
&in_list) { if (NULL == root) { return; } _get_in_order_list(root->left, in_list); in_list.push_back(root->val); _get_in_order_list(root->right, in_list); } int kthSmallest(TreeNode* root, int k) { vector
in_list; _get_in_order_list(root, in_list); return in_list[k - 1]; }};

 

转载于:https://www.cnblogs.com/SpeakSoftlyLove/p/5215278.html

你可能感兴趣的文章
A Simple OpenGL Shader Example
查看>>
资料整理面试
查看>>
理解JavaScript中的事件处理
查看>>
lock: mutex/spinlock/shared lock
查看>>
基于JAVA的身份证实名认证接口调用代码实例
查看>>
Shell命令-文件压缩解压缩之tar、unzip
查看>>
挺有意思的一段VBS代码,让系统阅读/朗读指定文本
查看>>
mysql体系结构
查看>>
CSS实现图片半透明代码
查看>>
hdu 4135 Co-prime (素数打表+容斥原理)
查看>>
manacher算法求最长回文子串
查看>>
(转)IDataGridViewEditingControl 接口 作用
查看>>
ie兼容性问题的一些总结,待添加。后续有图
查看>>
获取客户端IP
查看>>
【论文阅读】StainGAN: Stain Style Transfer for Digital Histological Images
查看>>
细节性的错误
查看>>
c++中string的用法
查看>>
oracle中if/else功能的实现的3种写法
查看>>
获取当前控制器
查看>>
装机快捷键
查看>>