# 563. Binary Tree Tilt

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.

Example:

``````Input:
1
/   \
2     3
Output: 1
Explanation:
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1
``````

Note:

1. The sum of node values in any subtree won’t exceed the range of 32-bit integer.
2. All the tilt values won’t exceed the range of 32-bit integer.

``````class Solution {
public:
unordered_map<TreeNode*, int> m;
int findTilt(TreeNode* root) {
if (!root) return 0;
int tilt = abs(getSum(root->left, m) - getSum(root->right, m));
return tilt + findTilt(root->left) + findTilt(root->right);
}
int getSum(TreeNode* node, unordered_map<TreeNode*, int>& m) {
if (!node) return 0;
if (m.count(node)) return m[node];
return m[node] = getSum(node->left, m) + getSum(node->right, m) + node->val;
}
};
``````

``````class Solution {
public:
int findTilt(TreeNode* root) {
int res = 0;
postorder(root, res);
return res;
}
int postorder(TreeNode* node, int& res) {
if (!node) return 0;
int leftSum = postorder(node->left, res);
int rightSum = postorder(node->right, res);
res += abs(leftSum - rightSum);
return leftSum + rightSum + node->val;
}
};
``````

https://discuss.leetcode.com/topic/87191/java-o-n-postorder-traversal

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation