|
1 | 1 | package com.fishercoder.solutions; |
2 | 2 |
|
3 | 3 | import com.fishercoder.common.classes.TreeNode; |
| 4 | + |
4 | 5 | import java.util.ArrayList; |
5 | 6 | import java.util.List; |
6 | 7 |
|
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 | | - */ |
30 | 8 | 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 | + } |
39 | 17 |
|
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 | + } |
50 | 29 | } |
51 | | - } |
52 | 30 | } |
0 commit comments