-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Time: 35 ms (41.53%), Space: 73.5 MB (91.95%) - LeetHub
- Loading branch information
1 parent
b42367c
commit daa2604
Showing
1 changed file
with
53 additions
and
0 deletions.
There are no files selected for viewing
53 changes: 53 additions & 0 deletions
53
2641-cousins-in-binary-tree-ii/2641-cousins-in-binary-tree-ii.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
/** | ||
* Definition for a binary tree node. | ||
* public class TreeNode { | ||
* int val; | ||
* TreeNode left; | ||
* TreeNode right; | ||
* TreeNode() {} | ||
* TreeNode(int val) { this.val = val; } | ||
* TreeNode(int val, TreeNode left, TreeNode right) { | ||
* this.val = val; | ||
* this.left = left; | ||
* this.right = right; | ||
* } | ||
* } | ||
*/ | ||
class Solution { | ||
public TreeNode replaceValueInTree(TreeNode root) { | ||
dfs(new TreeNode[] {root}); | ||
root.val = 0; | ||
return root; | ||
} | ||
|
||
private void dfs(TreeNode[] arr) { | ||
if (arr.length == 0) return; | ||
|
||
int sum = 0; | ||
for (TreeNode node : arr) { | ||
if (node == null) continue; | ||
if (node.left != null) sum += node.left.val; | ||
if (node.right != null) sum += node.right.val; | ||
} | ||
|
||
TreeNode[] children = new TreeNode[arr.length * 2]; | ||
int i = 0; | ||
|
||
for (TreeNode node : arr) { | ||
int curr = 0; | ||
if (node.left != null) curr += node.left.val; | ||
if (node.right != null) curr += node.right.val; | ||
|
||
if (node.left != null) { | ||
node.left.val = sum - curr; | ||
children[i++] = node.left; | ||
} | ||
if (node.right != null) { | ||
node.right.val = sum - curr; | ||
children[i++] = node.right; | ||
} | ||
} | ||
|
||
dfs(java.util.Arrays.copyOf(children, i)); | ||
} | ||
} |