diff --git a/1120-Maximum-Average-Subtree/cpp-1120/CMakeLists.txt b/1120-Maximum-Average-Subtree/cpp-1120/CMakeLists.txt new file mode 100644 index 00000000..a9faeff1 --- /dev/null +++ b/1120-Maximum-Average-Subtree/cpp-1120/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1120-Maximum-Average-Subtree/cpp-1120/main.cpp b/1120-Maximum-Average-Subtree/cpp-1120/main.cpp new file mode 100644 index 00000000..b610c81d --- /dev/null +++ b/1120-Maximum-Average-Subtree/cpp-1120/main.cpp @@ -0,0 +1,70 @@ +/// Source : https://leetcode.com/problems/maximum-average-subtree/ +/// Author : liuyubobobo +/// Time : 2019-07-13 + +#include +#include + +using namespace std; + + +/// DFS +/// Time Complexity: O(n) +/// Space Complexity: O(n) + +/// 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 { + +private: + unordered_map sum; + unordered_map sz; + +public: + double maximumAverageSubtree(TreeNode* root) { + + dfsSum(root); + dfsSz(root); + return dfsRes(root); + } + +private: + int dfsSum(TreeNode* node){ + + if(!node) return 0; + int left = dfsSum(node->left); + int right = dfsSum(node->right); + sum[node] = left + right + node->val; + return sum[node]; + } + + int dfsSz(TreeNode* node){ + + if(!node) return 0; + int left = dfsSz(node->left); + int right = dfsSz(node->right); + sz[node] = left + right + 1; + return sz[node]; + } + + double dfsRes(TreeNode* node){ + + if(!node) return 0; + double left = dfsRes(node->left); + double right = dfsRes(node->right); + return max(max(left, right), (double)sum[node] / sz[node]); + } +}; + + +int main() { + + return 0; +} \ No newline at end of file diff --git a/readme.md b/readme.md index 0fe29c1c..1b62cea3 100644 --- a/readme.md +++ b/readme.md @@ -764,4 +764,5 @@ email: [liuyubobobo@gmail.com](mailto:liuyubobobo@gmail.com) | | | | | | | | 1118 | [Number of Days in a Month](https://leetcode.com/problems/number-of-days-in-a-month/) | [无] | [C++](1118-Number-of-Days-in-a-Month/cpp-1118/) | | | | 1119 | [Remove Vowels from a String](https://leetcode.com/problems/remove-vowels-from-a-string/) | [无] | [C++](1119-Remove-Vowels-from-a-String/cpp-1119/) | | | +| 1120 | [Maximum Average Subtree](https://leetcode.com/problems/maximum-average-subtree/) | [无] | [C++](1120-Maximum-Average-Subtree/cpp-1120/) | | | | | | | | | | \ No newline at end of file