思路:二叉搜索树的中序遍历是有序的从大到小的,故得出中序遍历的结果,即要第cnt大的数为倒数第cnt的数
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/
class Solution {
public://用于保存中序遍历结果vector<int> inorder;int findTargetNode(TreeNode* root, int cnt) {//进行中序遍历getorder(root);//返回中序遍历中倒数第cnt个数即为所求的结果return inorder[inorder.size()-cnt];}//进行中序遍历void getorder(TreeNode* root){ if(root == nullptr) return;getorder(root->left);inorder.push_back(root->val);getorder(root->right);}
};