LeetCode 872 Leaf-Similar Trees

题意

给定两颗二叉树, 判断其叶子节点的序列是否是一致的.

例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
树1:
4
/ \
2 7
/ \
1 3

叶子节点序列为 [1, 3, 7]

树2:
9
/ \
6 7
/ \
1 3

叶子节点序列为 [1, 3, 7]


两棵树叶子节点序列相同, 返回 true.

解法

本题主要考察的是对树的遍历,遍历获取所有叶子节点,并比较是否一致即可。下面给出递归和非递归两种实现方式。

递归写法 (DFS):

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; }
* }
*/
public class Solution {
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
ArrayList<Integer> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
dfs(root1, list1);
dfs(root2, list2);
return list1.equals(list2);
}

private void dfs(TreeNode root, ArrayList<Integer> list) {
if (root == null) {
return;
}

if (root.left == null && root.right == null) {
list.add(root.val);
}

dfs(root.left, list);
dfs(root.right, list);
}
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Leaf-Similar Trees.

Memory Usage: 37.3 MB, less than 6.16% of Java online submissions for Leaf-Similar Trees.

非递归写法:

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
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution2 {
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
ArrayList<Integer> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();

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

private void pushLeafRoot(TreeNode root, ArrayList<Integer> list) {
if (root == null) {
return;
}

Stack<TreeNode> stack = new Stack<>();
stack.push(root);

while (!stack.isEmpty()) {
TreeNode node = stack.pop();

if (node.left != null) {
stack.push(node.left);
}
if (node.right != null) {
stack.push(node.right);
}

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

Runtime: 1 ms, faster than 82.41% of Java online submissions for Leaf-Similar Trees.

Memory Usage: 36.7 MB, less than 71.02% of Java online submissions for Leaf-Similar Trees.

  • 本文作者: 赵俊
  • 本文链接: http://www.zhaojun.im/leetcode-872/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!