美文网首页Leetcode
Leetcode 501. Find Mode in Binar

Leetcode 501. Find Mode in Binar

作者: SnailTyan | 来源:发表于2018-12-07 18:53 被阅读2次

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Find Mode in Binary Search Tree

2. Solution

/**
 * 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);
    }
};

Reference

  1. https://leetcode.com/problems/find-mode-in-binary-search-tree/description/

相关文章

网友评论

    本文标题:Leetcode 501. Find Mode in Binar

    本文链接:https://www.haomeiwen.com/subject/vodxhqtx.html