diff options
author | crupest <crupest@outlook.com> | 2020-10-07 09:15:40 +0800 |
---|---|---|
committer | crupest <crupest@outlook.com> | 2020-10-07 09:15:40 +0800 |
commit | a14e4728ddc16d049b21d85dc82e5194f12dedde (patch) | |
tree | 81c7b24aafe33e4f540f47dc6c05b98004553005 | |
parent | aadfefe51f733bb480891ccdee417e0a65a180e6 (diff) | |
download | solutions-a14e4728ddc16d049b21d85dc82e5194f12dedde.tar.gz solutions-a14e4728ddc16d049b21d85dc82e5194f12dedde.tar.bz2 solutions-a14e4728ddc16d049b21d85dc82e5194f12dedde.zip |
Add problem 501 .
-rw-r--r-- | cpp/501.cpp | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/cpp/501.cpp b/cpp/501.cpp new file mode 100644 index 0000000..197ed10 --- /dev/null +++ b/cpp/501.cpp @@ -0,0 +1,58 @@ +#include <cstddef> +#include <vector> + +using std::vector; + +struct TreeNode +{ + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Solution +{ +public: + void dfs(TreeNode *node, int &last, int &count, int &max_count, vector<int> &result) + { + if (node == nullptr) + return; + + dfs(node->left, last, count, max_count, result); + + auto current = node->val; + if (current == last) + { + count += 1; + } + else + { + count = 1; + } + + if (count == max_count) + { + result.push_back(current); + } + else if (count > max_count) + { + max_count = count; + result.clear(); + result.push_back(current); + } + + last = current; + dfs(node->right, last, count, max_count, result); + } + + vector<int> findMode(TreeNode *root) + { + if (root == nullptr) + return {}; + int last = 0, count = 0, max_count = 0; + vector<int> result; + dfs(root, last, count, max_count, result); + return result; + } +}; |