--- tags: leetcode --- # [501. Find Mode in Binary Search Tree](https://leetcode.com/problems/find-mode-in-binary-search-tree/) --- # My Solution ## The Key Idea for Solving This Coding Question ## C++ Code ```cpp= /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<int> findMode(TreeNode *root) { predecessorVal = -200000; repeatCnt = 1; maxRepeat = 1; dfs(root); return answer; } private: int predecessorVal; int repeatCnt; int maxRepeat; vector<int> answer; void dfs(TreeNode *root) { if (root == nullptr) { return; } dfs(root->left); if (predecessorVal == root->val) { ++repeatCnt; } else { repeatCnt = 1; } if (maxRepeat < repeatCnt) { maxRepeat = repeatCnt; answer.clear(); answer.push_back(root->val); } else if (maxRepeat == repeatCnt) { answer.push_back(root->val); } predecessorVal = root->val; dfs(root->right); } }; ``` ## Time Complexity $O(n)$ $n$ is the number of nodes in the binary tree referred by `root`. ## Space Complexity $O(H)$ $H$ is the height of the binary tree referred by `root`. # Miscellane <!-- # Test Cases ``` [1,null,2,2] ``` ``` [0] ``` ``` [1,0,1,0,0,1,1,0] ``` ``` [1,null,2] ``` ``` [1,1,2,0,null,2,2] ``` -->