-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDistributeCandiesInABinaryTree.java
More file actions
44 lines (36 loc) · 1.06 KB
/
Copy pathDistributeCandiesInABinaryTree.java
File metadata and controls
44 lines (36 loc) · 1.06 KB
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
40
41
42
43
44
//User function Template for Java
/*
class Node {
int data;
Node left;
Node right;
Node(int data) {
this.data = data;
left = null;
right = null;
}
}*/
class Solution
{
public static int distributeCandy(Node root)
{
//code here
int[] moves = new int[1]; // Using an array to pass by reference
distributeCandyUtil(root, moves);
return moves[0];
}
private static int distributeCandyUtil(Node node, int[] moves)
{
if (node == null) {
return 0;
}
int leftMoves = distributeCandyUtil(node.left, moves);
int rightMoves = distributeCandyUtil(node.right, moves);
// Calculate moves needed for the current node
int nodeMoves = Math.abs(leftMoves) + Math.abs(rightMoves);
// Update moves array with the moves needed for the current node
moves[0] += Math.abs(leftMoves) + Math.abs(rightMoves);
// Return the excess candies at the current node
return node.data + leftMoves + rightMoves - 1;
}
}