↓Skip to main content
  1. LeetCode/

LeetCode 2331: Evaluate Boolean Binary Tree

·1 min· ·
LeetCode Easy Tree Depth-First-Search Binary-Tree
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-11-18

  • Submissions: Accepted (first try)

Approach
#

Post-order: evaluate both subtrees, then apply OR or AND by the node’s value (Tree Template 1). The tree is full (every internal node has two children), and a leaf’s value is its result.

My Solution
#

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

Complexity
#

Time O(n), space O(h).

Mistakes to Avoid
#

  • Checking for a left child identifies leaves, since internal nodes always have both.

Interview Explanation
#

Leaves return their own boolean; internal nodes evaluate both children and apply OR or AND, in a post-order recursion. Time O(n).

Related

LeetCode 1379: Find a Corresponding Node of a Binary Tree in a Clone of That Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 1379 note: walk both trees in lockstep; when the original reaches target, the clone’s node at the same position is the answer, comparing node identity
LeetCode 1022: Sum of Root To Leaf Binary Numbers
·2 mins
LeetCode Easy Tree Depth-First-Search Binary-Tree
LeetCode 1022 note: on the way down double the current number and add the node’s bit, adding it to the total at a leaf
LeetCode 938: Range Sum of BST
·2 mins
LeetCode Easy Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 938 note: prune with the BST order, going only right below low and only left above high, adding nodes inside the range
LeetCode 965: Univalued Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 965 note: every value must equal the root’s; compare values while recursing, not the booleans the recursion returns
LeetCode 993: Cousins in Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 993 note: cousins share a depth but not a parent; record x’s and y’s depth and parent during DFS and compare
LeetCode 872: Leaf-Similar Trees
·1 min
LeetCode Easy Tree Depth-First-Search Binary-Tree
LeetCode 872 note: collect leaves left to right with DFS; BFS collects level by level, which is not left-to-right order