leetcode 腾讯50题 42/50二叉树第k大值
作者:互联网
题目描述
给定一棵二叉查找树,实现一个实现查询树中第k小的方法kthSmallest。
注意
假设 k 总是合法,即1 ≤ k ≤ BST的总元素个数。
样例
Example 1:
Input: root = [3,1,4,null,2], k = 1
3
/
1 4
2
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/
3 6
/
2 4
/
1
Output: 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:
int kthSmallest(TreeNode* root, int k) {
vector<TreeNode*> nodeList;
dfs(root,nodeList);
return nodeList[k-1]->val;
}
void dfs(TreeNode* cur,vector<TreeNode*>& nodeList){
if(cur->left) dfs(cur->left,nodeList);
nodeList.push_back(cur);
if(cur->right) dfs(cur->right,nodeList);
}
};
标签:right,TreeNode,cur,int,大值,50,dfs,二叉树,nodeList 来源: https://blog.csdn.net/qq_34673038/article/details/90205985