Skip to content

Commit

Permalink
1120 added.
Browse files Browse the repository at this point in the history
  • Loading branch information
liuyubobobo committed Jul 14, 2019
1 parent a098eb1 commit 7feca7b
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 0 deletions.
6 changes: 6 additions & 0 deletions 1120-Maximum-Average-Subtree/cpp-1120/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
cmake_minimum_required(VERSION 3.14)
project(C)

set(CMAKE_CXX_STANDARD 14)

add_executable(C main.cpp)
70 changes: 70 additions & 0 deletions 1120-Maximum-Average-Subtree/cpp-1120/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/// Source : https://leetcode.com/problems/maximum-average-subtree/
/// Author : liuyubobobo
/// Time : 2019-07-13

#include <iostream>
#include <unordered_map>

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<TreeNode*, int> sum;
unordered_map<TreeNode*, int> 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;
}
1 change: 1 addition & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -764,4 +764,5 @@ email: [[email protected]](mailto:[email protected])
| | | | | | |
| 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/) | | |
| | | | | | |

0 comments on commit 7feca7b

Please sign in to comment.