剑指offer54

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 /*bst比较经典的题目 先要统计每个节点的字节点的个数 然后递归顺序查找即可*/
 /*耽误很长时间的坑是 不要忘记预处理计算和顺序查找时 当前节点+1 非常容易出错*/
class Solution {
public:
    int son_count(unordered_map<TreeNode * , int>  &son_num , TreeNode * root){
        
        if(root -> right == NULL && root -> left == NULL){
             son_num.insert(pair<TreeNode * , int>(root , 0));
             return 0;
        }
        else if(root -> right == NULL){
             int L =  son_count(son_num , root -> left);
             son_num.insert(pair<TreeNode * , int>(root , L+1));
             return L + 1;
        }
        else if(root -> left == NULL){
             int R = son_count(son_num , root -> right);
             son_num.insert(pair<TreeNode * , int>(root , R+1));
             return R + 1;
        }
        else{
            int L = son_count(son_num , root -> left);
            int R = son_count(son_num , root -> right);
            son_num.insert(pair<TreeNode * , int>(root , L+R+2));
            return L + R + 2;
        }
    }

    int findKth(unordered_map<TreeNode * , int>  &son_num , TreeNode * root ,int k){
         int left_num = 0;
         int right_num = 0;

         if(root -> left != NULL) left_num = son_num[root -> left] + 1;
         
         
         int ans = 0;
         if(k == left_num + 1)
             ans =  root -> val;
         else if(k < left_num + 1)
             ans = findKth(son_num , root->left , k);
         else /*k > left_num + 1*/
             ans = findKth(son_num , root-> right , k - left_num - 1);

        return ans;
         
    }
    int kthLargest(TreeNode* root, int k) {
           unordered_map<TreeNode * , int> son_num;
           int cnt  = son_count(son_num , root) + 1;
           //printf("%d \n" , cnt);
           k = cnt - k + 1;
           //printf("%d \n" , k);
           int ans = findKth(son_num , root , k);
           return ans;
           
    }
};

 

posted on 2020-11-17 10:14  在苏州的城边  阅读(81)  评论(0编辑  收藏  举报

导航