LeetCode 230. Kth Smallest Element in a BST

题目

题意:判断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);
        }
         
    }
};
原文地址:https://www.cnblogs.com/dacc123/p/12409719.html