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

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

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?

 

Analyse:

Trial 1: We can first sort the sequence by inorder traversal and find the k-th element.

    Runtime: 24ms

1 /** 2  * Definition for a binary tree node. 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     int kthSmallest(TreeNode* root, int k) {13         if(!root) return 0;14         vector
result;15 inorder(root, result);16 return result[k - 1];17 }18 void inorder(TreeNode* root, vector
& result){19 if(!root) return;20 inorder(root->left, result);21 result.push_back(root->val);22 inorder(root->right, result);23 }24 };

 

Trial 2: Do the inorder process iterately, set a count number, when it equals to k, return corresponding value.

         Runtime: 24ms.

1 /** 2  * Definition for a binary tree node. 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     int kthSmallest(TreeNode* root, int k) {13         if(!root) return 0;14         stack
stk;15 int order = 0;16 while(!stk.empty() || root){17 if(root){18 stk.push(root);19 root = root->left;20 }21 else{22 root = stk.top();23 stk.pop();24 order++;25 if(order == k) return root->val;26 root = root->right;27 }28 }29 }30 };

 

转载于:https://www.cnblogs.com/amazingzoe/p/4698615.html

你可能感兴趣的文章
c++ 子类构造函数初始化及父类构造初始化
查看>>
Analysis on Human Various Emotional Expression
查看>>
DataGridView DataGridViewCheckBoxColumn编辑时实时触发事件
查看>>
SignalR---服务端
查看>>
PlayerPrefs存储Vector3等结构数据
查看>>
LightOJ - 1422 Halloween Costumes (区间DP)
查看>>
Dubbo架构设计详解
查看>>
谁终将点燃闪电,必长久如云漂泊
查看>>
小诗句集萃四
查看>>
软件之美: 易用性设计的目标及准则
查看>>
异步回调,事件,线程池与协程
查看>>
matlab函数:c2d离散化函数(待完善)
查看>>
java并发多面性
查看>>
TFS 测试用例导入、导出工具
查看>>
java -jstack
查看>>
C#中线程调用带有参数的方法
查看>>
单片机的模块化编程
查看>>
[转]从3个IT公司里学到的57条经验
查看>>
Test指令
查看>>
c++11——可变参数模板
查看>>