leetcode-872-Leaf-Similar-Trees

描述


Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.

img

For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).

Two binary trees are considered leaf-similar if their leaf value sequence is the same.

Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.

Note:

  • Both of the given trees will have between 1 and 100 nodes.

分析


先序,中序,后序遍历都可以。

解决方案1(Java)


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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
List<Integer> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();

preOrder(root1, list1);
preOrder(root2, list2);
return list1.equals(list2);
}

public void preOrder(TreeNode node, List list) {
if (node == null) {
return;
}

if (node.left == null && node.right == null) {
list.add(node.val);
}
preOrder(node.left, list);
preOrder(node.right, list);
}
}

题目来源