Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5df19a2

Browse files
committed
check cousins in tree
1 parent 81351af commit 5df19a2

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
'use strict';
2+
class Node {
3+
constructor(data) {
4+
this.data = data;
5+
this.leftNode = this.rightNode = null;
6+
}
7+
}
8+
9+
function isSibling(root, a, b) {
10+
if (root == null) return true;
11+
return ((root.leftNode && root.rightNode)
12+
|| (root.leftNode.data == a && root.rightNode.data == b)
13+
|| (root.rightNode.data == a && root.leftNode.data == b)
14+
|| isSibling(root.leftNode, a, b)
15+
|| isSibling(root.rightNode, a, b))
16+
}
17+
18+
function findLevel(root, data, level) {
19+
if (root == null) return 0;
20+
if (root.data == data) return level;
21+
let levelResult = findLevel(root.leftNode, data, level + 1);
22+
if (levelResult != 0) return levelResult;
23+
return findLevel(root.rightNode, data, level + 1);
24+
}
25+
26+
function isCousin(root, a, b) {
27+
if (root == null) return false;
28+
let aLevel = findLevel(root, a, 1);
29+
let bLevel = findLevel(root, b, 1);
30+
if (aLevel == bLevel && (isSibling(root, a, b))) return true;
31+
return false;
32+
}
33+
34+
//level - 1
35+
let tree = new Node(20);
36+
37+
// level - 2
38+
tree.leftNode = new Node(8);
39+
tree.rightNode = new Node(6);
40+
41+
// level -3
42+
tree.leftNode.leftNode = new Node(3);
43+
tree.leftNode.rightNode = new Node(5);
44+
45+
tree.rightNode.leftNode = new Node(2);
46+
// 20
47+
// / \
48+
// 8 6
49+
// / \ /
50+
// 3 5 2
51+
let a = 3, b = 2;
52+
console.log(a + ' and ' + b + ' is cousins = ', isCousin(tree, a, b));

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /