Leetcode 501. Find Mode in Binary Search Tree

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/84885649

文章作者: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/
阅读更多

扫码向博主提问

SnailTyan

博客专家

非学,无以致疑;非问,无以广识
  • 擅长领域:
  • 深度学习
  • PyTorch
  • OCR
  • Docker
  • Caffe
去开通我的Chat快问

没有更多推荐了,返回首页