0
点赞
收藏
分享

微信扫一扫

LeetCode 230. Kth Smallest Element in a BST

归零者245号 2022-10-18 阅读 185

​​题目​​

题意:判断BST中第k大的节点

题解:中序遍历

/**
* 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 pos;
int ans;
int kthSmallest(TreeNode* root, int k) {

DFS(root,k);
return ans;
}

void DFS(TreeNode* root,int k)
{
if(root->left!=NULL)
{
DFS(root->left,k);
}
pos++;
if(pos==k)
{
ans=root->val;
return;
}

if(root->right!=NULL)
{
DFS(root->right,k);
}

}
};



举报

相关推荐

0 条评论