LeetCode C++ 1302. Deepest Leaves Sum【Tree/BFS/DFS】中等
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
.
題意:給定一棵二叉樹,返回層數最深的葉子節點的和。
解法1 BFS
計算每一層中可能的葉子節點的和,最後一層即為所求結果:
class Solution {
public:
int deepestLeavesSum(TreeNode* root) {
if (root == nullptr) return 0;
int ans = 0;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int size = q.size(), leavesSum = 0;
for (int i = 0; i < size; ++i) {
TreeNode *t = q.front(); q.pop(); //其實不必額外判斷是否是葉子節點; 最後一層無疑都是葉子節點
if (!t->left && !t->right) { leavesSum += t->val; continue; }
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
ans = leavesSum;
}
return ans;
}
};
效率如下:
執行用時:64 ms, 在所有 C++ 提交中擊敗了90.93% 的使用者
記憶體消耗:38.8 MB, 在所有 C++ 提交中擊敗了14.18% 的使用者
解法2 DFS
不斷更新最大層數,同時記錄最大層對應的葉子節點值之和:
class Solution {
private:
int sum = 0, maxLevel = 0;
void dfs(TreeNode* root, int level) {
if (root == nullptr) return;
if (level > maxLevel) {
maxLevel = level;
sum = root->val;
} else if (level == maxLevel) sum += root->val;
dfs(root->left, level + 1);
dfs(root->right, level + 1);
}
public:
int deepestLeavesSum(TreeNode* root) {
dfs(root, 0);
return sum;
}
};
執行結果如下:
執行用時:64 ms, 在所有 C++ 提交中擊敗了90.93% 的使用者
記憶體消耗:38.1 MB, 在所有 C++ 提交中擊敗了34.94% 的使用者
相關文章
- LeetCode之Sum of Left Leaves(Kotlin)LeetCodeKotlin
- LeetCode C++ 968. Binary Tree Cameras【Tree/DFS】困難LeetCodeC++
- Sum of Left Leaves
- LeetCode#110.Balanced Binary Tree(Tree/Height/DFS/Recursion)LeetCode
- 404-Sum of Left Leaves
- leetcode-124-Binary Tree Maximum Path SumLeetCode
- LeetCode 124. Binary Tree Maximum Path SumLeetCode
- DAG bfs + dfs 126,
- leetcode刷題記錄:演算法(六)BFS&DFSLeetCode演算法
- LeetCode C++ 376. Wiggle Subsequence【Dynamic Programming】中等LeetCodeC++
- LeetCode C++ 50. Pow(x, n)【Recursion】中等LeetCodeC++
- LeetCode C++ 56. Merge Intervals【排序/陣列】中等LeetCodeC++排序陣列
- 求樹的直徑(BFS/DFS)
- 聊聊演算法——BFS和DFS演算法
- LeetCode C++ 316. Remove Duplicate Letters【Stack/Greedy/String】中等LeetCodeC++REM
- 藍橋杯-迷宮(BFS+DFS)
- LeetCode C++ 33. Search in Rotated Sorted Array【二分】中等LeetCodeC++
- leetcode Sum系列LeetCode
- Leetcode Path SumLeetCode
- 速記圖的遍歷(DFS和BFS)
- js解leetcode(32)-中等JSLeetCode
- ABC359 G - Sum of Tree Distance
- Leetcode 39 Combination SumLeetCode
- Leetcode 1 two sumLeetCode
- LeetCode | 1 Two SumLeetCode
- hdu 6446 Tree and Permutation(dfs+思維)
- Codefroces 1328E Tree Querie(dfs序)
- 【LeetCode】416. Partition Equal Subset Sum 解題報告(Python & C++)LeetCodePythonC++
- JAVA圖搜尋演算法之DFS-BFSJava演算法
- LeetCode C++ 劍指 Offer 64. 求1+2+…+n【Bit Manipulation】中等LeetCodeC++
- leetcode-39-Combination SumLeetCode
- Leetcode 40 Combination Sum IILeetCode
- Leetcode 15 3SumLeetCode
- Leetcode 18 4SumLeetCode
- LeetCode-1 Two SumLeetCode
- LeetCode 112. Path SumLeetCode
- [LeetCode]1.Two SumLeetCode
- python: leetcode - 1 Two SumPythonLeetCode