Leetcode 501. Find Mode in Binary Search Tree | | Leetcode 501. Find Mode in Binary Search Tree 文章作者:Tyan博客:noahsnail.com | CSDN | 简书 1. Description 2. Solution1234567891011121314151617181920212223242526272829303132333435363738394041424344454647/** * 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 https://leetcode.com/problems/find-mode-in-binary-search-tree/description/ 如果有收获,可以请我喝杯咖啡! 赏 微信打赏 支付宝打赏