Binary Tree Tilt (LeetCode 563): Interview Notes

Binary Tree Tilt (LeetCode 563): Interview Notes

LinkjobAI

Binary Tree Tilt (LeetCode 563): tilt of a node = |left_sum - right_sum|; return total tilt.

def findTilt(root):
    ans = 0
    def dfs(n):
        nonlocal ans
        if not n: return 0
        L, R = dfs(n.left), dfs(n.right)
        ans += abs(L - R)
        return n.val + L + R
    dfs(root)
    return ans

Postorder sums keep O(n) and O(h) stack.

Reference Linkjob.

(Affiliation: I work on Linkjob AI.)

Report Page