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);
        }
         
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章