> For the complete documentation index, see [llms.txt](https://hao-fu-1.gitbook.io/oj/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hao-fu-1.gitbook.io/oj/binary_tree_and_divide_conquer/divide-and-concquer/binary-tree-tilt.md).

# Binary Tree Tilt

<https://leetcode.com/problems/binary-tree-tilt/description/>

> Given a binary tree, return the tilt of the whole tree.
>
> The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.
>
> The tilt of the whole tree is defined as the sum of all nodes' tilt.

## Thoughts

tilt是左子树所有结点的和和右子树所有结点的和的差。\
如果我们有当前结点左子树的和和右子树的和，就直接相减即可。\
所以问题转为对于给定结点，如何求它所在子树的和。\
同样用分治法即可。

## Code

```
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int tilt = 0;

    private int sumTree(TreeNode node) {
        if (node == null) {
            return 0;
        }

        int left = sumTree(node.left);
        int right = sumTree(node.right);      

        int sum = node.val + left;
        sum += right;

        tilt += Math.abs(left - right); 
        return sum;
    }

    public int findTilt(TreeNode root) {
        sumTree(root);

        return tilt;
    }
}
```

## Analysis

时间复杂度O(n)

## Ver.2

<https://discuss.leetcode.com/topic/89648/java-solution-no-globle-varible-easy-and-clean>

没有global variable的分治解法.

```
public int findTilt(TreeNode root) {
        if (root == null) return 0;
        int curVal = 0;
        curVal = Math.abs(sumSubTree(root.left) - sumSubTree(root.right));
        return curVal + findTilt(root.left) + findTilt(root.right);
    }

    private int sumSubTree(TreeNode root) {
        if (root == null) return 0;
        return root.val + sumSubTree(root.left) + sumSubTree(root.right);
    }
```

## Ver.3

stack + map的iterative 版本.

```
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int findTilt(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int tilt = 0;
        Stack<TreeNode> stack = new Stack<>();
        Map<TreeNode, Integer> map = new HashMap<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.peek();
            if ((node.left == null || map.containsKey(node.left)) &&
                (node.right == null || map.containsKey(node.right))) {
                stack.pop();
                int left = map.containsKey(node.left) ? map.get(node.left) : 0;
                int right = map.containsKey(node.right) ? map.get(node.right) : 0;
                tilt += Math.abs(left - right);
                map.remove(node.left);
                map.remove(node.right);
                map.put(node, left + right + node.val);
            } else {
                if (node.left != null && !map.containsKey(node.left)) {
                    stack.push(node.left); 
                }

                if (node.right != null && !map.containsKey(node.right)) {
                    stack.push(node.right);
                }      
            }
        }
        return tilt;
    }
}
```

时间复杂度O(N), 空间stack消耗O(N), map消耗2^(k-1).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hao-fu-1.gitbook.io/oj/binary_tree_and_divide_conquer/divide-and-concquer/binary-tree-tilt.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
