[LeetCode-230]Kth Smallest Element in a BST
来源:互联网 发布:qt初学者 知乎 编辑:程序博客网 时间:2024/05/22 12:23
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?
Solution:
/** * 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 tree_size(TreeNode* root){ if (root){ return tree_size(root->left) + tree_size(root->right) + 1; } else { return 0; } } int kthSmallest(TreeNode* root, int k) { if (tree_size(root->left) + 1 == k) { return root->val; } else if (tree_size(root->left) + 1 > k) { return kthSmallest(root->left, k); } else { return kthSmallest(root->right, k-(tree_size(root->left)+1)); } }};
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
- 设计模式六大原则(3):依赖倒置原则
- java中的静态块
- MySQL外键设置中的的 Cascade、NO ACTION、Restrict、SET NULL
- c#中调用DLL
- 静态语言和动态语言
- [LeetCode-230]Kth Smallest Element in a BST
- 常用java编译器总结
- jsf ActionListener 查找正确的UIComponent
- iOS 上传头像处理
- 149,关闭键盘
- iOS高级开发——CollectionView的cell长按事件实现
- iOS 动画效果弹出提示视图
- Linux命令小计
- Struts回顾