class Solution {
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
List leafSequence1 = new ArrayList<>();
List leafSequence2 = new ArrayList<>();
getLeafSequence(root1, leafSequence1);
getLeafSequence(root2, leafSequence2);
return leafSequence1.equals(leafSequence2);
}
private void getLeafSequence(TreeNode node, List leafSequence) {
if (node == null) return;
if (node.left == null && node.right == null) {
leafSequence.add(node.val);
} else {
getLeafSequence(node.left, leafSequence);
getLeafSequence(node.right, leafSequence);
}
}
}
Текст:
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence.
For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8). Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.
Мой код проходит все тесты кроме двух последних.