Given a binary tree, return the tilt of the whole tree.
The tilt of a tree node is defined as the absolute difference
The tilt of the whole tree
Example:
Input:
1
/ \
2 3
Output: 1
Explanation:
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.
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiI0gTMx81dsQWZ4lmZf1GLlpXazVmcvwFciV2dsQXYtJ3bm9CX9s2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xCMy81dvRWYoNHLwEzX5xCMx8FesU2cfdGLwMzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsYTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cGcq5CM0ADOyUmY1ATMkJGOhRDMzYzX1ITNxgTMzIzLchDMyIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjLyM3Lc9CX6MHc0RHaiojIsJye.jpg)
方法1:递归的方式,一边累加tilt的值,一边求左、右子树的和。代码如下。一个很明显的问题是,在求左右子树和时,树被遍历了多次。比如,求1的左右子树和时,需要遍历2、4、5、3;在求2的左右子树和时需要遍历4、5,可见4、5被遍历了两遍。
public static int findTilt(TreeNode root) {
if(root == null) {
return 0;
}
return findTilt(root.left) + findTilt(root.right) +
Math.abs(sum(root.left) - sum(root.right));
}
public static int sum(TreeNode root) {
if(root == null) {
return 0;
}
return root.val + sum(root.left) + sum(root.right);
}
int tilt = 0;
public int findTilt(TreeNode root) {
sum(root);
return tilt;
}
public int sum(TreeNode root) {
if(root == null) {
return 0;
}
int l = sum(root.left);
int r = sum(root.right);
tilt += Math.abs(l - r);
return