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

LeetCode 2331: Evaluate Boolean Binary Tree

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

基本資料
#

難易度: easy 第一次嘗試:2022-11-18

  • 提交紀錄:Accepted(一次通過)

解題思路
#

後序:先算左右子樹,再依照節點的值做 OR 或 AND(Tree 模板一)。題目保證是完整的二元樹(每個內部節點都有兩個小孩),葉子的值就是結果。

我的解法
#

class Solution:
    def evaluateTree(self, root: Optional[TreeNode]) -> bool:
        if not root.left:
            return bool(root.val)
        l, r = self.evaluateTree(root.left), self.evaluateTree(root.right)
        return l or r if root.val == 2 else l and r

複雜度
#

時間 O(n),空間 O(h)。

要特別避免的錯誤
#

  • 判斷葉子只要看有沒有左小孩,因為內部節點一定有兩個小孩。

面試口說整理
#

葉子直接回傳自己的布林值,內部節點先算左右再做 OR 或 AND,用遞迴後序計算。時間 O(n)。

相關文章

LeetCode 1379: Find a Corresponding Node of a Binary Tree in a Clone of That Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 1379 解題筆記:兩棵樹同時走,原樹走到 target 時,複製樹上的同一個位置就是答案;比的是節點本身
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 收集的順序是一層一層,不是由左到右