Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 1c41133

Browse files
committedSep 7, 2022
Runtime: 179 ms (Top 13.99%) | Memory: 158.1 MB (Top 58.04%)
1 parent 9de6331 commit 1c41133

File tree

1 file changed

+10
-11
lines changed

1 file changed

+10
-11
lines changed
 
Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// Runtime: 179 ms (Top 13.99%) | Memory: 158.1 MB (Top 58.04%)
12

23
class Solution {
34
public TreeNode canMerge(List<TreeNode> trees) {
@@ -6,15 +7,14 @@ public TreeNode canMerge(List<TreeNode> trees) {
67
for(TreeNode t : trees){
78
map.put(t.val, t);
89
}
9-
10+
1011
// Merge trees
1112
for(TreeNode t : trees){
1213
if(map.containsKey(t.val)){
1314
merger(t, map);
1415
}
1516
}
1617

17-
1818
//After merging we should have only one tree left else return null
1919
if(map.size() != 1) return null;
2020
else {
@@ -26,12 +26,11 @@ public TreeNode canMerge(List<TreeNode> trees) {
2626
} else return null;
2727
}
2828
}
29-
29+
3030
return null;
31-
32-
31+
3332
}
34-
33+
3534
void merger(TreeNode t, HashMap<Integer, TreeNode> map){
3635
map.remove(t.val); // Remove current tree to prevent cyclical merging For. 2->3(Right) and 3->2(Left)
3736
//Merge on left
@@ -41,9 +40,9 @@ void merger(TreeNode t, HashMap<Integer, TreeNode> map){
4140
t.left = map.get(t.left.val);
4241
map.remove(t.left.val);
4342
}
44-
43+
4544
// Merge on right
46-
if(t.right!=null && map.containsKey(t.right.val) ){
45+
if(t.right!=null && map.containsKey(t.right.val) ){
4746
// Before merging child node, merge the grandchild nodes
4847
merger(map.get(t.right.val), map);
4948
t.right = map.get(t.right.val);
@@ -52,15 +51,15 @@ void merger(TreeNode t, HashMap<Integer, TreeNode> map){
5251
// Add tree back to map once right and left merge is complete
5352
map.put(t.val, t);
5453
}
55-
54+
5655
// Validate BST
5756
public boolean isValidBST(TreeNode root) {
5857
return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
5958
}
60-
59+
6160
public boolean helper(TreeNode root, long min, long max){
6261
if(root == null) return true;
6362
if(root.val <= min || root.val >= max) return false;
6463
return helper(root.left, min, root.val) && helper(root.right, root.val, max);
6564
}
66-
}
65+
}

0 commit comments

Comments
 (0)
Please sign in to comment.