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】 Surrounded Regions (BFS && DFS)LeetCode
- LeetCode C++ 968. Binary Tree Cameras【Tree/DFS】困難LeetCodeC++
- Clone Graph leetcode java(DFS and BFS 基礎)LeetCodeJava
- Leetcode Binary Tree Maximum Path SumLeetCode
- Leetcode-Bianry Tree Maximum Path SumLeetCode
- Binary Tree Maximum Path Sum leetcode javaLeetCodeJava
- leetcode刷題記錄:演算法(六)BFS&DFSLeetCode演算法
- LeetCode#110.Balanced Binary Tree(Tree/Height/DFS/Recursion)LeetCode
- 資料結構學習(C++)——圖【2】(DFS和BFS) (轉)資料結構C++
- 聊聊演算法——BFS和DFS演算法
- leetcode-124-Binary Tree Maximum Path SumLeetCode
- LeetCode 124. Binary Tree Maximum Path SumLeetCode
- 藍橋杯-迷宮(BFS+DFS)
- LeetCode C++ 50. Pow(x, n)【Recursion】中等LeetCodeC++
- 【DFS】HDU 5423 Rikka with Tree
- hdu1258 Sum It Up (DFS)
- LeetCode C++ 56. Merge Intervals【排序/陣列】中等LeetCodeC++排序陣列
- LeetCode C++ 33. Search in Rotated Sorted Array【二分】中等LeetCodeC++
- JAVA圖搜尋演算法之DFS-BFSJava演算法
- js解leetcode(32)-中等JSLeetCode
- LeetCode練習-中等卷LeetCode
- LeetCode C++ 376. Wiggle Subsequence【Dynamic Programming】中等LeetCodeC++
- NOIP2010引水入城[BFS DFS 貪心]
- C++演算法——BFSC++演算法
- Leetcode Path SumLeetCode
- leetcode Sum系列LeetCode
- Leetcode Two SumLeetCode
- Codefroces 1328E Tree Querie(dfs序)
- LeetCode C++ 316. Remove Duplicate Letters【Stack/Greedy/String】中等LeetCodeC++REM
- leetcode15&16_3Sum&4SumLeetCode
- 深度DFS 和 廣度BFS搜尋演算法學習演算法
- ABC359 G - Sum of Tree Distance
- LeetCode C++ 劍指 Offer 64. 求1+2+…+n【Bit Manipulation】中等LeetCodeC++
- Leetcode 1 two sumLeetCode
- Leetcode 3SumLeetCode
- Leetcode 4SumLeetCode
- Leetcode Path Sum IILeetCode