思路:定义一个中序遍历的函数,调用中序遍历将各个节点都存在VECTOR中,其中的数是从小到大的排列的,再取第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 kthSmallest(TreeNode* root, int k) {
int c;
if(root==NULL) c=0;
else inorder(root,k,0,c);
return c;
}
/*int inorder(TreeNode* root,int k)
{ vector<int> a;
stack<TreeNode*> s;
int l=0;
if(root==NULL) return 0;
while(!s.empty()||root!=NULL)
{
while(!root)
{
s.push(root);
root=root->left;
}
root=s.top();
s.pop();
a.push_back(root->val);
l++;
if(l==k) break;
root=root->right;
}
return root->val;
}
*/
void inorder(TreeNode* root,int k,int a,int res)
{
if(root==NULL||a>k) return;
inorder(root->left,k,a,res);
a++;
if(a==k) res==root->val;
inorder(root->right,k,a,res);
}
};