diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /max_sum_binary_tree.cpp | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'max_sum_binary_tree.cpp')
-rw-r--r-- | max_sum_binary_tree.cpp | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/max_sum_binary_tree.cpp b/max_sum_binary_tree.cpp new file mode 100644 index 0000000..64d1d20 --- /dev/null +++ b/max_sum_binary_tree.cpp @@ -0,0 +1,26 @@ +// 1161. Maximum Level Sum of a Binary Tree +#include "leetcode.h" + +/* + * given the 'root' of a binary tree, the level of its root is 1, the level of + * its children is 2, and so on. return the smallest level 'x' such that the sum + * of all the values of nodes at level 'x' is maximal. + */ + +class Solution { + vector<int> sums; + void dfs(TreeNode *root, size_t level) { + if (root) { + sums.resize(max(sums.size(), level)); + sums[level - 1] += root->val; + dfs(root->left, level + 1); + dfs(root->right, level + 1); + } + } + +public: + int maxLevelSum(TreeNode *root) { + dfs(root, 1); + return distance(begin(sums), max_element(begin(sums), end(sums))) + 1; + } +}; |