Find Mode in Binary Search Tree

2019-05-25 22:38:57 浏览数 (1)

1. Description

2. Solution

代码语言:javascript复制
/**
 * 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<int> findMode(TreeNode* root) {
        vector<int> modes;
        if(!root) {
            return modes;
        }
        int count = 0;
        int max = 0;
        int prev = 0;
        inorder(root, modes, count, max, prev);
        return modes;
    }

private:
    void inorder(TreeNode* root, vector<int>& modes, int& count, int& max, int& prev) {
        if(!root) {
            return;
        }
        inorder(root->left, modes, count, max, prev);
        if(root->val == prev) {
            count  ;
        }
        else {
            count = 1;
        }
        if(count > max){
            modes.clear();
            max = count;
            modes.push_back(root->val);
        }
        else if(count == max) {
            modes.push_back(root->val);
        }
        prev = root->val;
        inorder(root->right, modes, count, max, prev);
    }
};

0 人点赞