230. Kth Smallest Element in a BST 难度:medium
来源:互联网 发布:万网域名管理平台入口 编辑:程序博客网 时间:2024/05/22 07:56
题目:
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.
思路:
1、计算左子树元素个数left。
2、 left+1 = K,则根节点即为第K个元素
left >=k, 则第K个元素在左子树中,
left +1 <k, 则转换为在右子树中,寻找第K-left-1元素。
程序:
/** * 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 calcTreeSize(TreeNode* root){ if (root == NULL) return 0; return 1+calcTreeSize(root->left) + calcTreeSize(root->right); } int kthSmallest(TreeNode* root, int k) { if (root == NULL) return 0; int leftSize = calcTreeSize(root->left); if (k == leftSize+1){ return root->val; }else if (leftSize >= k){ return kthSmallest(root->left,k); }else{ return kthSmallest(root->right, k-leftSize-1); } } };
0 0
- 230. Kth Smallest Element in a BST 难度:medium
- Leetcode 230. Kth Smallest Element in a BST (Medium) (cpp)
- 378. Kth Smallest Element in a Sorted Matrix 难度:medium
- [Leetcode 230, Medium] Kth Smallest Element in a BST
- leetcode230:Kth Smallest Element in a BST(medium)
- Kth Smallest Element in a BST——Difficulty:Medium
- LeetCode #230 - Kth Smallest Element in a BST - Medium
- 230.Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- asp截取四位,谁能告诉我这是为什么?
- 组合结构图
- 游戏的收藏功能
- slothjson - 为懒人打造的json对象序列化神器
- 适配器中定义的ViewHolder为static相比于非static有什么好处?
- 230. Kth Smallest Element in a BST 难度:medium
- 大神们,IOS 能不能捕获全局异常
- 基于WindowsMediaPlayer网页播放器的设计与实现
- UIImageView空白处不要点击事件
- 17. Letter Combinations of a Phone Number**
- cocos2d-x 编译时出错
- 通信图
- 从《NOI2014 魔法森林》看动态树(LCT)的简单应用
- Linux命令格式