LeetCode 993 Cousins in Binary Tree

题意

给予一颗二叉树,和两个节点的值,判断这两个节点是否是堂兄弟,即在同一层,但父节点不同

例 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
给予树, x = 3, y = 4:

1
/ \
2 3
/
4

返回 false.


给予树, x = 5, y = 4:

1
/ \
2 3
\ \
4 5

返回 true.

解法

采用广度优先遍历, 要点是记录节点与父节点的对应关系, 然后判断是否在同一层, 这里采用队列来实现.

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
44
45
46
47
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isCousins(TreeNode root, int x, int y) {
if (root == null) {
return false;
}

HashMap<Integer, Integer> valParentMap = new HashMap<>();

Queue<TreeNode> queue = new ArrayDeque<>();
queue.add(root);

while(!queue.isEmpty()) {
int size = queue.size();

List<Integer> list = new ArrayList<>();

for (int i = 0; i < size; i++) {
TreeNode node = queue.remove();
list.add(node.val);

if (node.left != null) {
queue.add(node.left);
valParentMap.put(node.left.val, node.val);
}

if (node.right != null) {
queue.add(node.right);
valParentMap.put(node.right.val, node.val);
}
}

if (list.containsAll(Arrays.asList(x, y)) && !valParentMap.get(x).equals(valParentMap.get(y))) {
return true;
}
}
return false;
}
}

Runtime: 3 ms, faster than 68.73% of Java online submissions for Cousins in Binary Tree.
Memory Usage: 34.7 MB, less than 98.52% of Java online submissions for Cousins in Binary Tree.

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