AcWing 70. 二叉搜索树的第k个结点
原题链接
简单
作者:
daniellee
,
2019-04-17 00:27:03
,
所有人可见
,
阅读 1663
算法1
(中序遍历) $O(n)$
C++ 代码
/**
* 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 dfs(vector<int>& v,int k,TreeNode* root){
if (v.size() == k){
res = v[v.size()-1];
return;
}
if (!root) return;
if(root){
dfs(v,k,root->left);
// cout<<root->val<<endl;
v.push_back(root->val);
dfs(v,k,root->right);
}
}
int res = 0;
TreeNode* kthNode(TreeNode* root, int k) {
vector<int> v;
dfs(v,k,root);
// res = v[v.size()-1];
TreeNode *p = new TreeNode(res);
return p;
}
};