Leetcode 501. Find Mode in Binary Search Tree

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

1. Description

Leetcode 501. Find Mode in Binary Search Tree_第1张图片

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 findMode(TreeNode* root) {
        vector 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& 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/

你可能感兴趣的:(Algorithm)