leetcode 230 Kth Smallest Element in a BST
来源:互联网 发布:php社交系统 编辑:程序博客网 时间:2024/05/21 17:56
230. 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?
解题思路:
中序遍历即可
/** * 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 dp(TreeNode* root, int& k){ if(root==NULL)return 0; if(root->left!=NULL){ //左孩子不为空 int n=dp(root->left,k); if(k<1)return n; } if(k--==1)return root->val; else return dp(root->right,k); } int kthSmallest(TreeNode* root, int k) { return dp(root,k); }};
0 0
- #leetcode#Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- Leetcode|Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- 【LeetCode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- leetcode: Kth Smallest Element in a BST
- Leetcode: Kth Smallest Element in a BST
- [LeetCode] Kth Smallest Element in a BST
- [LeetCode]Kth Smallest Element in a BST
- [Leetcode]Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- [Leetcode]Kth Smallest Element in a BST
- Leetcode: Kth Smallest Element in a BST
- 深入浅出MFC:再来一发~~~MFC的Persistence(永久保存)机制
- iOS 25个性能优化/内存优化常用方法
- 深圳三日游暨炮灰面试记录
- test1 problem B tour (bitset+乱搞)
- AQWS_NOTE
- leetcode 230 Kth Smallest Element in a BST
- bzoj3675: [Apio2014]序列分割
- 关于api-ms-win-crt-runtimel1-1-0.dll缺失的解决方案
- 0013解析
- 采用Spring实现AOP功能
- 静态、动态、cglib代理
- 赛码网练习——向量表示
- 采用Spring管理Bean和依赖注入
- bitmap 小结