-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindTilt.java
More file actions
39 lines (35 loc) · 835 Bytes
/
Copy pathFindTilt.java
File metadata and controls
39 lines (35 loc) · 835 Bytes
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int totalTilt = 0;
public class Answer{
int tilt;
int sum;
}
public int findTilt(TreeNode root) {
Answer ans = findTiltHelper(root);
return this.totalTilt;
}
public Answer findTiltHelper(TreeNode root){
Answer ans = new Answer();
if (null==root) {
ans.sum = 0;
ans.tilt = 0;
}
else{
Answer leftans = findTiltHelper(root.left);
Answer rightans = findTiltHelper(root.right);
ans.tilt = Math.abs(leftans.sum-rightans.sum);
this.totalTilt+=ans.tilt;
ans.sum = leftans.sum+rightans.sum+root.val;
}
return ans;
}
}