Leetcode 刷题之Hash and Tree

本文探讨了LeetCode中使用哈希表和树解决的问题,包括滑动窗口问题如349. Intersection of Two Arrays,以及哈希表相关题目如242. Valid Anagram,同时还涵盖了树形结构的题目,如二叉树的层次遍历和最长单值路径等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

滑动窗口

349. Intersection of Two Arrays

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        set<int> rec(nums1.begin(),nums1.end());
        set<int> res;
        for(int idx = 0; idx < nums2.size(); idx++) {
            if(rec.find(nums2[idx]) != rec.end()) {
                res.insert(nums2[idx]);
            }
        }
        return vector<int>(res.begin(), res.end());
    }
};

350. Intersection of Two Arrays II

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        map<int,int>mp1;
        vector<int> res;
        for(int idx = 0; idx < nums1.size(); idx++) {
            mp1[nums1[idx]]++;
        }
        for(int idx = 0; idx < nums2.size(); idx++) {
            if(mp1[nums2[idx]] > 0) {
                res.push_back(nums2[idx]);
                mp1[nums2[idx]]--;
            }
        }
        return res;
    }
};

map的时间复杂度是O(nlogn),空间复杂度是O(n),底层实现是二叉平衡树。
unordered_map的时间复杂度是O(n),空间复杂度是O(n),底层实现是哈希表。

242. Valid Anagram

class Solution {
public:
    bool isAnagram(string s, string t) {
        map<char, int> rec;
        for(int idx = 0; idx < s.size(); idx++) {
            rec[s[idx]]++;
        }
        for(int idx = 0; idx < t.size(); idx++) {
            rec[t[idx]]--;
            if(rec[t[idx]] < 0) {
                return false;
            }
        }
        for(map<char,int>::iterator it = rec.begin(); it != rec.end(); it++) {
            if(it->second) {
                return false;
            }
        }
        return true;
    }
};

202. Happy Number

class Solution {
public:
    bool isHappy(int n) {
        set<int> rec;
        while(1) {
            string str = to_string(n);
            int tmp = 0;
            for(char c:str) {
                tmp += (c - '0')*(c - '0');
            }
            if(tmp == 1) {
                return true;
            }
            if(rec.find(tmp) == rec.end()) {
                rec.insert(tmp);
            }
            else {
                return false;
            }
            n = tmp;
        }

        return true;
    }
};

290. Word Pattern

class Solution {
public:
    vector<string> split(string str, string pattern)
    {
        string::size_type pos;
        vector<string> result;
        str += pattern;
        int size=str.size();

        for(int i=0; i<size; i++)
        {
            pos=str.find(pattern,i);
            if(pos<size)
            {
                string s = str.substr(i,pos-i);
                result.push_back(s);
                i = pos+pattern.size()-1;
            }
        }
        return result;
    }

    bool wordPattern(string pattern, string str) {
        map<char, string> rec;
        map<string, char> rec2;
        vector<string> strs = split(str, " ");
        if(strs.size() != pattern.size()) {
            return false;
        }
        for(int idx = 0; idx < pattern.size(); idx++) {
            if(rec.find(pattern[idx]) == rec.end()) {
                rec[pattern[idx]] = strs[idx];
            }
            else {
                if(rec[pattern[idx]].compare(strs[idx])) {
                    return false;
                }
            }
            if(rec2.find(strs[idx]) == rec2.end()) {
                rec2[strs[idx]] = pattern[idx];
            }
            else {
                if(rec2[strs[idx]] != pattern[idx]) {
                    return false;
                }
            }
        }
        return true;
    }
};

205. Isomorphic Strings

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        int s_len = s.size();
        int t_len = t.size();
        if(s_len != t_len) {
            return false;
        }
        map<char, char> rec1;
        map<char, char> rec2;
        for(int idx = 0; idx < s_len; idx++) {
            if(rec1.find(s[idx]) == rec1.end()) {
                rec1[s[idx]] = t[idx];    
            }
            else {
                if(rec1[s[idx]] != t[idx]) {
                    return false;
                }
            }
            if(rec2.find(t[idx]) == rec2.end()) {
                rec2[t[idx]] = s[idx];    
            }
            else {
                if(rec2[t[idx]] != s[idx]) {
                    return false;
                }
            }
        }
        return true;
    }
};

451. Sort Characters By Frequency

class Solution {
public:
    string copy_chars(int cnt, char c) {
        string res;
        for(int idx = 0; idx < cnt; idx++) {
            res += c;
        }
        return res;
    }

    string frequencySort(string s) {
        string res;
        map<char, int> rec;
        for(char c:s) {
            rec[c]++;
        }
        map<int,vector<char>> recs;
        for(map<char, int>::iterator it = rec.begin(); it != rec.end(); it++) {
            if(recs.find(it->second) == recs.end()) {
                vector<char> tmp;
                tmp.push_back(it->first);
                recs.insert(make_pair(it->second, tmp));
            }
            else {
                recs[it->second].push_back(it->first);
            }
        }
        map<int,vector<char>>::reverse_iterator rit;
        for (rit = recs.rbegin(); rit != recs.rend(); ++rit) {
            int count = rit->first;
            vector<char> chars = rit->second;
            for(vector<char>::iterator it = chars.begin(); it != chars.end(); it++) {
                res += copy_chars(count, *it);
            }
        }
        return res;
    }
};

哈希表

454. 4Sum II

class Solution {
public:
    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
        assert(A.size() == B.size() || B.size() == C.size() || 
               C.size() == D.size() || A.size() <= 500);
        unordered_map<int,int> rec;
        for(int idx1 = 0; idx1 < A.size(); idx1++) {
            for(int idx2 = 0; idx2 < B.size(); idx2++) {
                rec[A[idx1]+B[idx2]]++;
            }
        }
        int res = 0;
        for(int idx1 = 0; idx1 < C.size(); idx1++) {
            for(int idx2 = 0; idx2 < D.size(); idx2++) {
                int tar = -1*(C[idx1]+D[idx2]);
                if(rec.find(tar) != rec.end()) {
                    res += rec[tar];
                }
            }
        }
        return res;
    }
};

49. Group Anagrams

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> rec;
        vector<vector<string>> res;
        int len = strs.size();
        if(!len) {
            return res;
        }
        for(int i = 0; i < len; i++) {
            string tmp = strs[i];
            sort(tmp.begin(), tmp.end());
            if(rec.find(tmp) == rec.end()) {
                vector<string> new_item;
                new_item.push_back(strs[i]);
                rec[tmp] = new_item;
            }    
            else {
                rec[tmp].push_back(strs[i]);
            }    
        }    
        for(unordered_map<string, vector<string>>::iterator it = rec.begin(); it != rec.end(); it++) {
            res.push_back(it->second);
        }    
        return res;
    }
};

447. Number of Boomerangs

class Solution {
public:
    int distanceTwoPoints(pair<int, int> p1, pair<int, int> p2) {
        int res = (p1.first - p2.first)*(p1.first - p2.first);
        res += (p1.second - p2.second)*(p1.second - p2.second);
        return res;
    }    

    int numberOfBoomerangs(vector<pair<int, int>>& points) {
        int res = 0;
        int len = points.size();
        if(!len) {
            return res;
        }
        for(int i = 0; i < len; i++) {
            unordered_map<int, int> rec;
            for(int j = 0; j < len; j++) {
                if(i != j) {
                    int dis = distanceTwoPoints(points[i], points[j]);
                    rec[dis]++;
                }    
            }    
            for(unordered_map<int,int>::iterator it = rec.begin(); it != rec.end(); it++) {
                if(it->second >= 2) {
                    res += it->second * (it->second-1);
                }    
            }    
        }    
        return res;
    }
};

219. Contains Duplicate II

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_set<int> rec;
        int len = nums.size();
        for(int i = 0; i < len; i++) {
            if(rec.find(nums[i]) != rec.end()) {
                return true;
            }   
            rec.insert(nums[i]);
            if(rec.size() == k+1) {
                rec.erase(nums[i-k]);
            }    
        }
        return false;
    }
};

217. Contains Duplicate

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        set<int> rec;
        for(int i = 0; i < nums.size(); i++) {
            if(rec.find(nums[i]) != rec.end()) {
                return true;
            }
            rec.insert(nums[i]);
        }
        return false;
    }
};

438. Find All Anagrams in a String

class Solution {
public:
    vector<int> findAnagrams(string s, string p) {
        vector<int> res;
        int len_s = s.size();
        int len_p = p.size();
        unordered_map<char, int> rec; 
        int fin = -1;
        for(int idx = 0; idx < len_p; idx++) {
            rec[p[idx]]++;
        }
        for(int idx = 0; idx < len_s; idx++) {
            rec[s[idx]]--;  
            if(rec[s[idx]] == 0) {
                rec.erase(s[idx]);
                if(!rec.size()) {
                    res.push_back(idx-len_p+1);
                }    
            }    
            if(idx >= len_p-1) {
                rec[s[idx-len_p+1]]++; 
                if(rec[s[idx-len_p+1]] == 0) {
                    rec.erase(s[idx-len_p+1]);
                }    
            }    
        }    
        return res;
    }
};

220. Contains Duplicate III

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        set<long long> rec;
        int len = nums.size();
        long long tar = (long long)  t;
        for(int idx = 0; idx < len; idx++) {
            long long tmp_v = (long long) nums[idx];
            bool isContain = rec.lower_bound(tmp_v-tar) != rec.end();
            if(isContain) { 
                bool isLower = (long long)*rec.lower_bound(tmp_v-tar) <= tmp_v+tar;
                if(isLower) {
                    return true;
                }    
            }    
            rec.insert(tmp_v);
            if(rec.size() == k+1) {
                rec.erase(nums[idx-k]);
            }
        }   
        return false;
    }
};

149. Max Points on a Line

/**
 * Definition for a point.
 * struct Point {
 *     int x;
 *     int y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */
class Solution {
public:
    int gcd(int num1, int num2) {
        while (num2) {
            int temp = num2; 
            num2 = num1 % num2;
            num1 = temp;
        }
        return num1;
    }

    int maxPoints(vector<Point>& points) {
        int maxpt = 1;
        int len = points.size();
        if(!len) {
            return 0;
        }    
        for(int i = 0; i < len; i++) {
            map<pair<int, int>, int> rec;
            int rem = 0;
            for(int j = i +1; j < len; j++) {
                if(points[i].x == points[j].x && points[i].y == points[j].y) {
                    rem++;
                }
                else {
                    if(points[i].x == points[j].x) {
                        rec[make_pair(INT_MAX, points[i].x)]++;    
                    }   
                    else {
                        int diff_y = points[i].y - points[j].y;
                        int diff_x = points[i].x - points[j].x;
                        int gcd_v = gcd(diff_x, diff_y);
                        diff_x /= gcd_v;
                        diff_y /= gcd_v;
                        rec[make_pair(diff_x, diff_y)]++;   
                    }
                }
            }
            for(map<pair<int,int>,int>::iterator it = rec.begin(); it != rec.end(); it++) {
                maxpt = max(maxpt, it->second+rem+1);
            }  
            maxpt = max(maxpt, rem+1);
        }    
        return maxpt;
    }
};
/**
 * Definition for a point.
 * struct Point {
 *     int x;
 *     int y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */
class Solution {
public:
    int gcd(int num1, int num2) {
        while (num2) {
            int temp = num2; 
            num2 = num1 % num2;
            num1 = temp;
        }
        return num1;
    }

    int maxPoints(vector<Point>& points) {
        int maxpt = 1;
        int len = points.size();
        if(!len) {
            return 0;
        }    
        for(int i = 0; i < len; i++) {
            unordered_map<string, int> rec;
            int rem = 0;
            int vertical = 0;
            for(int j = i +1; j < len; j++) {
                if(points[i].x == points[j].x && points[i].y == points[j].y) {
                    rem++;
                }
                else {
                    if(points[i].x == points[j].x) {
                        vertical++;    
                    }   
                    else {
                        int diff_y = points[i].y - points[j].y;
                        int diff_x = points[i].x - points[j].x;
                        int gcd_v = gcd(diff_y, diff_x);
                        diff_y /= gcd_v;
                        diff_x /= gcd_v;
                        string key_s = to_string(diff_y) + " " + to_string(diff_x);
                        rec[key_s]++;
                    }
                }
            }
            for(unordered_map<string,int>::iterator it = rec.begin(); it != rec.end(); it++) {
                maxpt = max(maxpt, it->second+rem+1);
            }  
            maxpt = max(maxpt, rem+1);
            maxpt = max(maxpt, vertical+rem+1);
        }    
        return maxpt;
    }
};

LeetCode 748. Shortest Completing Word

class Solution {
private:
    bool match(vector<int>rec, string cur){
        for(auto c:cur){
            rec[tolower(c)-'a']--;
        }
        for(auto i:rec){
            if(i>0){
                return false;
            }
        }
        return true;
    }
public:
    string shortestCompletingWord(string licensePlate, vector<string>& words) {
        vector<int> rec(26,0);
        for(char c:licensePlate){
            if(isalpha(c)){
                rec[tolower(c)-'a']++;
            }
        }
        int min_len=INT_MAX;
        string ans;
        for(auto str:words){
            if(str.length()>=min_len) {
                continue;
            }
            if(!match(rec,str)){
                continue;
            }
            min_len=str.size();
            ans=str;
        }
        return ans;
    }
};

734. Sentence Similarity

class Solution {
public:
    bool areSentencesSimilar(vector<string>& words1, vector<string>& words2, vector<pair<string, string>> pairs) {
        int len1=words1.size();
        int len2=words2.size();
        if(len1!=len2){
            return false;
        }
        unordered_map<string,unordered_set<string>> rec;
        for(auto p:pairs){
            rec[p.first].insert(p.second);
            rec[p.second].insert(p.first);
        }
        for(int i=0;i<len1;i++){
            if(words1[i]==words2[i]){
                continue;
            }
            if(rec.find(words1[i])!=rec.end() && rec[words1[i]].count(words2[i])>0){
                continue;
            }    
            else {
                return false;
            }
        }
        return true;
    }
};

720. Longest Word in Dictionary

class Solution {
public:
    string longestWord(vector<string>& words) {
        string best;
        unordered_set<string> dict(words.begin(),words.end());
        for(auto str:dict){
            string prex;
            int len=str.size();
            if(len<best.size() ||
              (len==best.size() && str > best)){
                continue;
            }
            bool val=true;
            for(int i=0;i<len-1;i++){
                prex+=str[i];
                if(dict.count(prex)<=0){
                    val=false;
                    break;
                }
            }
            if(val){
                best=str;
            }
        }
        return best;
    }
};
class Trie {
public:
    Trie(): root_(new TrieNode()) {}

    void insert(const string& word) {
        TrieNode* p = root_.get();
        for (const char c : word) {
            if (!p->children[c - 'a'])
                p->children[c - 'a'] = new TrieNode();
            p = p->children[c - 'a'];
        }
        p->is_word = true;
    }

    bool hasAllPrefixes(const string& word) {
        const TrieNode* p = root_.get();
        for (const char c : word) {
            if (!p->children[c - 'a']) return false;
            p = p->children[c - 'a'];
            if (!p->is_word) return false;
        }
        return true;
    }    
private:
    struct TrieNode {
        TrieNode():is_word(false), children(26, nullptr){}

        ~TrieNode() {
            for (auto node : children)
                delete node;
        }

        bool is_word;
        vector<TrieNode*> children;
    };

    std::unique_ptr<TrieNode> root_;
};

class Solution {
public:
    string longestWord(vector<string>& words) {
        Trie trie;
        for (const string& word : words)
            trie.insert(word);

        string best;
        for (const string& word : words) {
            if (word.length() < best.length() 
            || (word.length() == best.length() && word > best))
                continue;
            if (trie.hasAllPrefixes(word))
                best = word;
        }

        return best;
    }
};

trees

655. Print Binary Tree

/**
 * 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:
    vector<vector<string>> printTree(TreeNode* root) {
        int h=getHight(root);
        int w=(1<<h)-1;
        vector<vector<string>> ans(h,vector<string>(w,""));
        fillMatrix(ans, 0, 0, w-1, root);
        return ans;
    }
private:
    void fillMatrix(vector<vector<string>>& mat, 
                    int dep, 
                    int stt, 
                    int fin,
                    TreeNode* root){
        if(!root || stt>fin){
            return;
        }
        int mid=(stt+fin)>>1;
        mat[dep][mid]=to_string(root->val);
        fillMatrix(mat, dep+1, stt, mid-1, root->left);
        fillMatrix(mat, dep+1, mid+1, fin, root->right);
    }    

    int getHight(TreeNode* root) {
        if(!root) {
            return 0;
        }
        return max(getHight(root->left),getHight(root->right))+1;
    }    
};

637. Average of Levels in Binary Tree

/**
 * 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:
    vector<double> averageOfLevels(TreeNode* root) {
        if(!root){
            return {};
        }    
        queue<TreeNode*> que;
        que.push(root);
        vector<double> ans;
        while(!que.empty()){
            int size=que.size();
            double level_sum=0.0;
            for(int i=0;i<size;i++){
                TreeNode* tp=que.front();
                que.pop();
                level_sum+=tp->val;
                if(tp->left){
                    que.push(tp->left);
                }
                if(tp->right){
                    que.push(tp->right);
                }
            }
            ans.push_back(level_sum/static_cast<double>(size));
        }    
        return ans;
    }
};
/**
 * 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 {
private:
    void dfs(vector<double>&ans,int dep,TreeNode* root,vector<int>&rec){
        if(!root){
            return;
        }
        if(ans.size()<dep+1){
            ans.push_back(root->val);
            rec.push_back(1);
        }    
        else {
            ans[dep]+=root->val;
            rec[dep]++;
        }
        dfs(ans,dep+1,root->left,rec);
        dfs(ans,dep+1,root->right,rec);
    }    
public:
    vector<double> averageOfLevels(TreeNode* root) {
        vector<double> ans;
        vector<int> rec;
        dfs(ans,0,root,rec);
        for(int i=0;i<ans.size();i++){
            ans[i]/=static_cast<double>(rec[i]);
        }    
        return ans;
    }
};

617. Merge Two Binary Trees

/**
 * 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* mergeTrees(TreeNode* t1, TreeNode* t2) {
        if(!t1 && !t2){
            return NULL;
        }    
        int val=((t1)?t1->val:0)+((t2)?t2->val:0);
        TreeNode* root=new TreeNode(val);
        root->left=mergeTrees(t1?t1->left:NULL, t2?t2->left:NULL);
        root->right=mergeTrees(t1?t1->right:NULL, t2?t2->right:NULL);
        return root;
    }
};
/**
 * 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* mergeTrees(TreeNode* t1, TreeNode* t2) {
        if(!t1) {
            return t2;
        }
        if(!t2){
            return t1;
        }    
        int val=t1->val+t2->val;
        TreeNode* root=t1; // new TreeNode(val);
        root->val=val;
        root->left=mergeTrees(t1->left, t2->left);
        root->right=mergeTrees(t1->right, t2->right);
        return root;
    }
};

606. Construct String from Binary Tree

/**
 * 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:
    string tree2str(TreeNode* t) {
        if(!t) {
            return "";
        }
        string s=to_string(t->val);
        const string str_l=tree2str(t->left);
        const string str_r=tree2str(t->right);
        if(!t->left && !t->right){
            return s;
        }
        if(!t->right){
            return s+"("+str_l+")";
        }
        return s+"("+str_l+")"+"("+str_r+")";
    }
};

404. Sum of Left Leaves

/**
 * 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 sumOfLeftLeaves(TreeNode* root) {
        if(!root){
            return 0;
        }
        int sum=0;
        if(root->left){
            if(!root->left->left && !root->left->right){
                sum=root->left->val;
            }    
        }    
        sum+= sumOfLeftLeaves(root->right)+sumOfLeftLeaves(root->left);
        return sum;
    }
};

100. Same Tree

/**
 * 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:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(!p && !q){
            return true;
        }
        if(!p || !q) {
            return false;
        }
        if(p->val != q->val){
            return false;
        }    
        if(!isSameTree(p->left,q->left) ||
            !isSameTree(p->right,q->right)) {
            return false;
        }    
        return true;
    }
};
/**
 * 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:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(!p && !q){
            return true;
        }
        if(!p || !q) {
            return false;
        }
        if(p->val != q->val){
            return false;
        }    
        return isSameTree(p->left,q->left) &&
            isSameTree(p->right,q->right);
    }
};

110. Balanced Binary Tree

/**
 * 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 length(TreeNode*root){
        if(!root){
            return 0;
        }
        return max(length(root->left),length(root->right))+1;
    }    
    bool isBalanced(TreeNode* root) {
        if(!root){
            return true;
        }    
        bool ans=isBalanced(root->left) && isBalanced(root->right); 
        if(!ans){
            return false;
        }    
        return abs(length(root->left)-length(root->right))<=1;
    }
};
/**
 * 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 length(TreeNode*root, bool* ans){
        if(!root){
            return 0;
        }
        int l=length(root->left,ans);
        int r=length(root->right,ans);
        if(abs(l-r)>1){
            *ans=false;
            return -1;
        }    
        return max(l,r)+1;
    }    
    bool isBalanced(TreeNode* root) {
        if(!root){
            return true;
        }    
        bool ans=true;
        length(root,&ans); 
        return ans;
    }
};

21. Merge Two Sorted Lists

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(!l1){
            return l2;
        }
        if(!l2){
            return l1;
        }
        ListNode* ans;
        if(l1->val < l2->val){
            ans=l1;
            ans->next=mergeTwoLists(l1->next,l2);
        }
        else {
            ans=l2;
            ans->next=mergeTwoLists(l1,l2->next);
        }    
        return ans;        
    }
};
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* res=new ListNode(0);
        ListNode* ans=res;
        while(l1 && l2){
            if(l1->val < l2->val){
                ans->next=l1;
                l1=l1->next;
            }
            else{
                ans->next=l2;
                l2=l2->next;
            }    
            ans=ans->next;
        }    
        if(l1) {
            ans->next=l1;
        }
        if(l2) {
            ans->next=l2;
        }
        return res->next;
    }
};

102. Binary Tree Level Order Traversal

/**
 * 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:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> ans;
        queue<TreeNode*> tmp;
        if(!root){
            return ans;
        }    
        tmp.push(root);
        while(!tmp.empty()){
            int s=tmp.size();
            vector<int> cur;
            for(int i=0;i<s;i++){
                TreeNode* node=tmp.front();
                tmp.pop();
                cur.push_back(node->val);
                if(node->left){
                    tmp.push(node->left);
                }
                if(node->right){
                    tmp.push(node->right);
                }
            }
            ans.push_back(cur);
        }    
        return ans;
    }
};
/**
 * 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 {
private:
    void traveseTree(vector<vector<int>>&ans, int dep, TreeNode* root){
        if(!root){
            return;
        }    
        if(ans.size()<dep+1){
            vector<int> cur;
            cur.push_back(root->val);
            ans.push_back(cur);
        }
        else {
            ans[dep].push_back(root->val);
        }
        traveseTree(ans, dep+1, root->left);
        traveseTree(ans, dep+1, root->rigth);
    }    
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> ans;
        queue<TreeNode*> tmp;
        if(!root){
            return ans;
        }    
        traveseTree(ans,0,root);    
        return ans;
    }
};
/**
 * 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 {
private:
    void traveseTree(vector<vector<int>>&ans, int dep, TreeNode* root){
        if(!root){
            return;
        }    
        if(ans.size()<dep+1){
            ans.push_back({});
        }
        ans[dep].push_back(root->val);
        traveseTree(ans, dep+1, root->left);
        traveseTree(ans, dep+1, root->right);
    }    
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> ans;
        queue<TreeNode*> tmp;
        if(!root){
            return ans;
        }    
        traveseTree(ans,0,root);    
        return ans;
    }
};

671. Second Minimum Node In a Binary Tree

/**
 * 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 {
private:
    int dfs(TreeNode*root,int s){
        if(!root){
            return -1;
        }   
        if(root->val > s){
            return root->val;
        }    
        int l=dfs(root->left,s);
        int r=dfs(root->right,s);
        if(l==-1){
            return r;
        }
        if(r==-1){
            return l;
        }
        return min(l,r);
    }
public:
    int findSecondMinimumValue(TreeNode* root) {
        if(!root){
            return -1;
        }
        return dfs(root,root->val);
    }
};

669. Trim a Binary Search Tree

/**
 * 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* trimBST(TreeNode* root, int L, int R) {
        if(!root){
            return NULL;
        }    
        TreeNode* ans;
        if(root->val>=L&&root->val<=R){
            root->left=trimBST(root->left,L,R);
            root->right=trimBST(root->right,L,R);
            ans=root;
        }
        else if(root->val<L){
            ans=trimBST(root->right,L,R);
        }   
        else{
            ans=trimBST(root->left,L,R);
        }    
        return ans;
    }
};

124. Binary Tree Maximum Path Sum

/**
 * 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 {
private:
    int maxPathSum(TreeNode*root, int &ans){
        if(!root){
            return 0;
        }
        int l=max(0,maxPathSum(root->left,ans));
        int r=max(0,maxPathSum(root->right,ans));
        int sum=l+r+root->val;
        ans=max(ans,sum);
        return max(l,r)+root->val;
    }    
public:
    int maxPathSum(TreeNode* root) {
        if(!root){
            return 0;
        }
        int ans=INT_MIN;
        maxPathSum(root, ans);
        return ans;
    }
};

687. Longest Univalue Path

/**
 * 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 {
private:
    int longestUnivaluePath(TreeNode* root, int &ans){
        if(!root){
            return 0;
        }
        int l=longestUnivaluePath(root->left,ans);
        int r=longestUnivaluePath(root->right,ans);
        int pl=0;
        int pr=0;
        if(root->left&&root->left->val==root->val){
            pl=l+1;
        }
        if(root->right&&root->right->val==root->val){
            pr=r+1;
        }
        ans=max(ans,pl+pr);
        return max(pl,pr);
    }   
public:
    int longestUnivaluePath(TreeNode* root) {
        if(!root){
            return 0;
        }
        int ans=0;
        longestUnivaluePath(root,ans);
        return ans;
    }
};

543. Diameter of Binary Tree

/**
 * 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 {
private:
    int calculateDiameter(TreeNode*root, int&ans) {
        if(!root){
            return -1;
        }
        int l=calculateDiameter(root->left,ans);
        int r=calculateDiameter(root->right,ans);
        ans=max(l+r+2,ans);
        return max(l,r)+1;
    }    
public:
    int diameterOfBinaryTree(TreeNode* root) {
        if(!root){
            return 0;
        }
        int ans=0;
        calculateDiameter(root,ans);
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值