↓快轉到主要內容
  1. LeetCode/

LeetCode 2236: Root Equals Sum of Children

·1 分鐘· ·
LeetCode Easy Tree Binary-Tree
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2025-12-17

  • 提交紀錄:Python Accepted → C++ Compile Error → C++ Accepted

解題思路
#

題目保證只有根和兩個子節點,直接比較 root.val 和兩個子節點的和就好。

我的嘗試
#

Python 一次通過。接著用 C++ 再寫一次,第一次少了分號,出現 Compile Error:

return (root->left->val + root->right->val) == root->val    // 少了 ;

正確解法
#

class Solution:
    def checkTree(self, root: Optional[TreeNode]) -> bool:
        return root.val == root.left.val + root.right.val
class Solution {
public:
    bool checkTree(TreeNode* root) {
        return root->val == root->left->val + root->right->val;
    }
};

複雜度
#

時間 O(1),空間 O(1)。

要特別避免的錯誤
#

  • C++ 存取指標的成員要用 ->,不是 .。
  • C++ 的 return 敘述結尾要有分號。

面試口說整理
#

題目保證樹只有三個節點,所以直接比較根的值和兩個子節點值的和,時間和空間都是 O(1)。

相關文章

LeetCode 1022: Sum of Root To Leaf Binary Numbers
·1 分鐘
LeetCode Easy Tree Depth-First-Search Binary-Tree
LeetCode 1022 解題筆記:往下走時目前的數字乘 2 加上節點的值,到葉子時加進總和
LeetCode 938: Range Sum of BST
·1 分鐘
LeetCode Easy Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 938 解題筆記:利用 BST 剪枝,節點比 low 小就只往右,比 high 大就只往左,在範圍內才加
LeetCode 965: Univalued Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 965 解題筆記:每個節點的值都要等於根的值;遞迴時比的是值,不是遞迴回傳的布林值
LeetCode 993: Cousins in Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 993 解題筆記:堂兄弟要同一層、但父節點不同;DFS 記錄 x 和 y 的深度與父節點再比較
LeetCode 872: Leaf-Similar Trees
·1 分鐘
LeetCode Easy Tree Depth-First-Search Binary-Tree
LeetCode 872 解題筆記:用 DFS 由左到右收集葉子;BFS 收集的順序是一層一層,不是由左到右
LeetCode 637: Average of Levels in Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 637 解題筆記:層序遍歷,每層加總除以節點數