Given a binary tree, return the sum of values of its deepest leaves.
Example 1:
Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] Output: 15
Constraints:
- The number of nodes in the tree is between
1
and10^4
. - The value of nodes is between
1
and100
.
Solution 1: Recursion
Time complexity: O(n)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Author: Huahua class Solution { public: int deepestLeavesSum(TreeNode* root) { int sum = 0; int max_depth = 0; function<void(TreeNode*, int)> dfs = [&](TreeNode* n, int d) { if (!n) return; if (d > max_depth) { max_depth = d; sum = 0; } if (d == max_depth) sum += n->val; dfs(n->left, d + 1); dfs(n->right, d + 1); }; dfs(root, 0); return sum; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment