https://leetcode.com/problems/binary-tree-tilt
X. https://discuss.leetcode.com/topic/87475/simple-java-solution-without-global-variable
https://discuss.leetcode.com/topic/87191/java-o-n-postorder-traversal
https://discuss.leetcode.com/topic/88059/java-postorder-traversal-easy-to-understand
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:
- The sum of node values in any subtree won't exceed the range of 32-bit integer.
- All the tilt values won't exceed the range of 32-bit integer.
X. https://discuss.leetcode.com/topic/87475/simple-java-solution-without-global-variable
https://discuss.leetcode.com/topic/87191/java-o-n-postorder-traversal
int tilt = 0;
public int findTilt(TreeNode root) {
postorder(root);
return tilt;
}
public int postorder(TreeNode root) {
if (root == null) return 0;
int leftSum = postorder(root.left);
int rightSum = postorder(root.right);
tilt += Math.abs(leftSum - rightSum);
return leftSum + rightSum + root.val;
}
X. O(N^2)https://discuss.leetcode.com/topic/88059/java-postorder-traversal-easy-to-understand
public int findTilt(TreeNode root) {
if(root==null) return 0;
return Math.abs(sum(root.left)-sum(root.right)) + findTilt(root.left) + findTilt(root.right);
}
public int sum(TreeNode root){
if(root==null) return 0;
return sum(root.left) + sum(root.right) + root.val;
}
http://www.szeju.com/index.php/other/25248188.html
水题一道,按照题意算一下左右子树的和然后做差,递归处理一下就算完了。只不过这样的时间复杂度较大,效率不是很高。
int findTilt(TreeNode* root) {
if (root == NULL) return 0;
return abs(findSum(root->right) - findSum(root->left)) + findTilt(root->left) + findTilt(root->right);
}
int findSum(TreeNode* root) {
if (root == NULL) return 0;
return findSum(root->left) + root->val + findSum(root->right);
}