Given two binary trees, return true if and only if they have the same leaf node sequence. Leaf nodes are defined as nodes with no children.
Example:
Input: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]
Output: true
Explanation:
The leaf sequence from both trees is [6, 7, 4, 9, 8].
TreeNode
objects.true
.false
.To determine if two trees have the same leaf sequence, we can:
Here’s how you can implement this in Java:
/**
* 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<>();
getLeaves(root1, leaves1);
getLeaves(root2, leaves2);
return leaves1.equals(leaves2);
}
private void getLeaves(TreeNode root, List<Integer> leaves) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
leaves.add(root.val);
}
getLeaves(root.left, leaves);
getLeaves(root.right, leaves);
}
}
getLeaves
for both root nodes, and finally checks if the two lists are equal. If they are, the trees have the same leaf node sequence; otherwise, they don’t.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?