Path

Math in it: Bitwise, Divmod

1457. Pseudo-Palindromic Paths in a Binary Tree (Medium)

Solution

Refer solution for 266. Palindrome Permutation (Easy).

def pseudoPalindromicPaths(self, root: Optional[TreeNode]) -> int:
    def recursion(node, path):
        nonlocal ans
        if node:
            path = (path) ^ (1 << node.val)
            if not node.left and not node.right:
                ans += path & (path - 1) == 0
            recursion(node.left, path) if node.left else None
            recursion(node.right, path) if node.right else None

    ans = 0
    recursion(root, 0)
    return ans

1022. Sum of Root To Leaf Binary Numbers (Easy)

def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
    def recursion(node):
        nonlocal total, cur_binary
        if node:
            cur_binary = 2 * cur_binary + node.val
            if not node.left and not node.right:
                total += cur_binary
            recursion(node.left)
            recursion(node.right)
            cur_binary //= 2

    cur_binary = total = 0
    recursion(root)
    return total

129. Sum Root to Leaf Numbers (Medium)

def sumNumbers(self, root: Optional[TreeNode]) -> int:
    def recursion(node):
        nonlocal total, cur_decimal
        if node:
            cur_decimal = 10 * cur_decimal + node.val
            if not node.left and not node.right:
                total += cur_decimal
            recursion(node.left)
            recursion(node.right)
            cur_decimal //= 10

    cur_decimal = total = 0
    recursion(root)
    return total