立一个flag(剪枝)
/**
* 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:
TreeNode *res;
bool flag;
void dfs(TreeNode *root, int &k){
if(!root || flag) return ;
dfs(root->left, k);
k -- ;
if(k == 0){
flag = true;
res = root;
return ;
}
dfs(root->right, k);
}
TreeNode* kthNode(TreeNode* root, int k) {
flag = false;
dfs(root, k);
return res;
}
};