-
-
Notifications
You must be signed in to change notification settings - Fork 608
/
Copy pathBinaryTreeTIlt.java
39 lines (33 loc) · 961 Bytes
/
BinaryTreeTIlt.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package problems.easy;
import problems.utils.TreeNode;
import java.util.HashMap;
import java.util.Map;
/**
* Created by sherxon on 4/23/17.
*/
public class BinaryTreeTIlt {
int sum=0;
Map<TreeNode, Integer> tilts= new HashMap<>();
Map<TreeNode, Integer> sums=new HashMap<>();
public static void main(String[] args) {
System.out.println((char) ('0' + 1));
}
public int findTilt(TreeNode root) {
if(root==null)return sum;
go(root);
return sum;
}
/**
* Do post-order traversal and keep track of value sums of each node.
* */
void go(TreeNode root){
if(root==null)return;
go(root.left);
go(root.right);
int leftSum=sums.getOrDefault(root.left, 0);
int rightSum=sums.getOrDefault(root.right, 0);
sums.put(root, leftSum + rightSum + root.val);
tilts.put(root, Math.abs(leftSum-rightSum));
sum+=tilts.get(root);
}
}