Binary Tree Tilt

easy tree dfs binary tree

Problem

Return the sum, over all nodes, of |sum(left subtree) − sum(right subtree)| — the tree's total tilt.

Inputroot = [1,2,3]
Output1
Tilt(1) = |2 − 3| = 1, leaves contribute 0 each.

def find_tilt(root):
    total = 0
    def s(node):
        nonlocal total
        if not node: return 0
        l, r = s(node.left), s(node.right)
        total += abs(l - r)
        return node.val + l + r
    s(root)
    return total
function findTilt(root) {
  let total = 0;
  function s(node) {
    if (!node) return 0;
    const l = s(node.left), r = s(node.right);
    total += Math.abs(l - r);
    return node.val + l + r;
  }
  s(root);
  return total;
}
class Solution {
    int total = 0;
    public int findTilt(TreeNode root) { s(root); return total; }
    int s(TreeNode n) {
        if (n == null) return 0;
        int l = s(n.left), r = s(n.right);
        total += Math.abs(l - r);
        return n.val + l + r;
    }
}
int total = 0;
int s(TreeNode* n) {
    if (!n) return 0;
    int l = s(n->left), r = s(n->right);
    total += abs(l - r);
    return n->val + l + r;
}
int findTilt(TreeNode* root) { total = 0; s(root); return total; }
Time: O(n) Space: O(h) recursion