-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
34 lines (29 loc) · 799 Bytes
/
Copy pathsolution.java
File metadata and controls
34 lines (29 loc) · 799 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
/*
class Node {
int data;
Node left;
Node right;
Node(int data) {
this.data = data;
left = null;
right = null;
}
}
*/
class Solution {
private long moves = 0; // accumulate total moves
// helper returns the balance for the subtree rooted at node
private int dfs(Node node) {
if (node == null) return 0;
int leftBal = dfs(node.left);
int rightBal = dfs(node.right);
moves += Math.abs(leftBal) + Math.abs(rightBal); // moves to/from children
int balance = node.data + leftBal + rightBal - 1; // after each node keeps 1 candy
return balance;
}
public int distCandy(Node root) {
moves = 0;
dfs(root);
return (int)moves;
}
}