LeetCode 230. Kth Smallest Element in a BST

阅读 185

2022-10-18

​​题目​​

题意:判断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)

0 0 举报