劍指 Offer 54. 二叉搜索樹的第k大節點

題目
給定一棵二叉搜索樹,請找出其中第k大的節點。
題解
好久沒打代碼了,練練手,知識點題目,中序遍歷。
遞歸

class Solution {
public:
    int ans = 0;
    int cnt = 0;
    int kthLargest(TreeNode* root, int k) {
        dfs(root,k);
        return ans;
    }
    void dfs(TreeNode* root,int k){
        if(root==nullptr) return ;
        if(root->right) dfs(root->right,k);
        cnt++;
        if(cnt==k) ans=root->val;
        if(root->left) dfs(root->left,k);
    }
};

單函數遞歸

class Solution {
public:
    int cnt = 0;
    int kthLargest(TreeNode* root, int k) {
        if(root == nullptr) return -1;
        int ans = 0;
        if(root->right) ans = kthLargest(root->right,k);
        if(cnt >= k) return ans;
        cnt++;
        if(cnt==k) return root->val;
        if(root->left) return kthLargest(root->left,k);
        return -1;
    }
    
};

迭代

class Solution {
public:
    int cnt = 0;
    int kthLargest(TreeNode* root, int k) {
        if(root == nullptr) return -1;
        int ans = 0;
        if(root->right) ans = kthLargest(root->right,k);
        if(cnt >= k) return ans;
        cnt++;
        if(cnt==k) return root->val;
        if(root->left) return kthLargest(root->left,k);
        return -1;
    }
    
};

對節點加變量 int sum 表示該節點子樹大小

class Solution {
public:
    int kthLargest(TreeNode* root, int k) {
        if(root == nullptr) return -1;

        int sum = 0;
        if(root->right==nullptr) sum = 0;
        else sum =  root->right->sum + 1;
        if(sum + 1 == k){
            return root->val;
        }else if(sum > k){
            return kthLargest(root->right,k);
        }else{
            return kthLargest(root->left,k-sum);
        }
    }
    
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章