Skip to content

Commit 8ba3500

Browse files
refactor 872
1 parent d61c969 commit 8ba3500

File tree

1 file changed

+20
-42
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+20
-42
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,30 @@
11
package com.fishercoder.solutions;
22

33
import com.fishercoder.common.classes.TreeNode;
4+
45
import java.util.ArrayList;
56
import java.util.List;
67

7-
/**
8-
* 872. Leaf-Similar Trees
9-
*
10-
* Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.
11-
*
12-
* 3
13-
* / \
14-
* 5 1
15-
* / \ / \
16-
* 6 2 9 8
17-
* / \
18-
* 7 4
19-
*
20-
* For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).
21-
*
22-
* Two binary trees are considered leaf-similar if their leaf value sequence is the same.
23-
*
24-
* Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.
25-
*
26-
* Note:
27-
*
28-
* Both of the given trees will have between 1 and 100 nodes.
29-
*/
308
public class _872 {
31-
public static class Solution1 {
32-
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
33-
List<Integer> leaves1 = new ArrayList<>();
34-
List<Integer> leaves2 = new ArrayList<>();
35-
preorder(root1, leaves1);
36-
preorder(root2, leaves2);
37-
return leaves1.equals(leaves2);
38-
}
9+
public static class Solution1 {
10+
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
11+
List<Integer> leaves1 = new ArrayList<>();
12+
List<Integer> leaves2 = new ArrayList<>();
13+
preorder(root1, leaves1);
14+
preorder(root2, leaves2);
15+
return leaves1.equals(leaves2);
16+
}
3917

40-
private void preorder(TreeNode root,
41-
List<Integer> leaves) {
42-
if (root == null) {
43-
return;
44-
}
45-
if (root.left == null && root.right == null) {
46-
leaves.add(root.val);
47-
}
48-
preorder(root.left, leaves);
49-
preorder(root.right, leaves);
18+
private void preorder(TreeNode root,
19+
List<Integer> leaves) {
20+
if (root == null) {
21+
return;
22+
}
23+
if (root.left == null && root.right == null) {
24+
leaves.add(root.val);
25+
}
26+
preorder(root.left, leaves);
27+
preorder(root.right, leaves);
28+
}
5029
}
51-
}
5230
}

0 commit comments

Comments
 (0)