-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeaf-similar-Trees.java
More file actions
45 lines (40 loc) · 1.33 KB
/
Leaf-similar-Trees.java
File metadata and controls
45 lines (40 loc) · 1.33 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
45
/**
* 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 boolean leafSimilar(TreeNode root1, TreeNode root2) {
List<Integer> leaves1 = new ArrayList<>();
List<Integer> leaves2 = new ArrayList<>();
// Collect leaves from both trees
collectLeaves(root1, leaves1);
collectLeaves(root2, leaves2);
// Compare the leaf sequences
return leaves1.equals(leaves2);
}
// Helper method to perform DFS and collect leaf values
private void collectLeaves(TreeNode node, List<Integer> leaves) {
if (node == null) {
return; // Base case: if the current node is null, return
}
// If the node is a leaf, add its value to the list
if (node.left == null && node.right == null) {
leaves.add(node.val);
} else {
// Recursively collect leaves from left and right subtrees
collectLeaves(node.left, leaves);
collectLeaves(node.right, leaves);
}
}
}