欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 501 二叉搜索树中的众数

程序员文章站 2022-05-20 16:17:53
...
  • 分析
    中序遍历,顺便使用几个变量进行信息记录
  • 代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution{
private:
    int pre;
    int num;
    int max;    
public:
    Solution():max(-1), num(0), pre(INT_MIN){}
    vector<int> findMode(TreeNode* root){
        vector<int> vec;
        traverse(root, vec);
        return vec;
    }

    void traverse(TreeNode* root, vector<int>& vec){
        if(root == nullptr) return;

        traverse(root -> left, vec);        
        if(pre == INT_MIN){
            pre = root -> val;
            num = 1;
            vec.push_back(pre);
            max = 1;
              
        }else{
            if(root -> val == pre){
                num++;
                if(num > max){
                    vec.clear();
                    vec.push_back(pre);
                    max = num;
                }else if(num == max){
                    vec.push_back(pre);
                }
            }else if(root -> val != pre){
                pre = root -> val;
                num = 1;
                if(num > max){
                    vec.clear();
                    vec.push_back(pre);
                    max = num;
                }else if(num == max){
                    vec.push_back(pre);
                }
            }
        }
        traverse(root -> right, vec);
    }
};
相关标签: #