Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence.
Example 1:
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
Constraints:
The number of nodes in each tree will be in the range [1, 200].
Both of the given trees will have values in the range [0, 200].
二叉树的叶子序列是叶子节点从左到右组成的序列,问两棵二叉树的叶子序列是否相同
思路:
DFS前序遍历节点,从左到右保存叶子节点到list,最后比较两个list是否相同
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
List<Integer> leaves1 = new ArrayList<>();
List<Integer> leaves2 = new ArrayList<>();
dfs(root1, leaves1);
dfs(root2, leaves2);
return leaves1.equals(leaves2);
}
void dfs(TreeNode root, List<Integer> leaves) {
if(root == null) return;
if(root.left == null && root.right == null) {
leaves.add(root.val);
}
dfs(root.left, leaves);
dfs(root.right, leaves);
}