230. Kth Smallest Element in a BST
来源:互联网 发布:数控pmc编程 编辑:程序博客网 时间:2024/05/21 14:47
1. 原题
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 element.
2. 分析
- 题目要求找出宽度优先树中的第K小的树。
- 在没有这棵树的数据的情况下不知道哪些数是存在的, 所以要确定第K个树, 必须要遍历一遍树。得到所有数之后排序就可以得到第K小的数了
- 宽度优先和深度优先的遍历都有规律可循, 分别判断根, 坐子树和右子树, 基本普通的遍历都是这个模式, 需要考虑的是退出情况还有传参的方式, 这里使用引用传参比较方便
if (root != NULL){ nums.push_back(root->val); } if (root->left != NULL) getNums(root->left, nums); if (root->right != NULL) getNums(root->right, nums);}
3.代码
/** * 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 getNums(TreeNode* root, vector<int>& nums){ if (root != NULL){ nums.push_back(root->val); } if (root->left != NULL) getNums(root->left, nums); if (root->right != NULL) getNums(root->right, nums); } int kthSmallest(TreeNode* root, int k) { vector<int> nums; int len = nums.size(); getNums(root, nums); sort(nums.begin(), nums.end()); return nums[k-1]; }};
阅读全文
0 0
- 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
- 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
- 2017我的前端心得体会
- sharepoint 2016 使用powershell导入列表命令发生改变
- Spring Boot 基础
- 使用Swiper库实现从右向左排列的列表块
- android6.0下SETTING_VERSION无法绑定变量
- 230. Kth Smallest Element in a BST
- 数据流中产生随机样本
- C++学习笔记--临时对象
- java反射学习笔记(2)----java中的静态加载类和动态加载类
- 5.9
- Win10+Qt5.8+OpenCV3.2配置过程
- <T extends Comparable<? super T>>泛型类型与<T extends Comparable<T>>的区别以及优越性
- 将二维字符串数组作为WPF ListView的ItemSource
- IDEA注释样例笔记