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 0644faf

Browse files
committed
add day seven
1 parent d60fb38 commit 0644faf

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,4 @@
77
- Day 4: [Number Complement](https://github.com/libterty/leetcode-challenge/blob/master/src/may/day-four/index.ts) :laughing:
88
- Day 5: [First Unique Character in a String](https://github.com/libterty/leetcode-challenge/blob/master/src/may/day-five/index.ts) :smirk:
99
- Day 6: [Majority Element](https://github.com/libterty/leetcode-challenge/blob/master/src/may/day-six/index.ts) :relaxed:
10+
- Day 7: [Cousins in Binary Tree](https://github.com/libterty/leetcode-challenge/blob/master/src/may/day-seven/index.ts) :hushed:

‎src/may/day-seven/index.ts

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {TreeNode} root
11+
* @param {number} x
12+
* @param {number} y
13+
* @return {boolean}
14+
*/
15+
16+
interface Cache {
17+
[key: number]: Child;
18+
}
19+
20+
interface Child {
21+
parent?: number;
22+
depth: number;
23+
}
24+
25+
export const isCousins = function (root, x, y): boolean {
26+
const cache: Cache = {};
27+
28+
if (root && root.val) cache[root.val] = { parent: null, depth: 0 };
29+
30+
const dfs = (node, depth: number = 1): void => {
31+
if (node && node.left) {
32+
cache[node.left.val] = { parent: node.val, depth };
33+
dfs(node.left, depth + 1);
34+
}
35+
36+
if (node && node.right) {
37+
cache[node.right.val] = { parent: node.val, depth };
38+
dfs(node.right, depth + 1);
39+
}
40+
};
41+
42+
if (root) dfs(root);
43+
else return false;
44+
45+
const depthOfx: number = cache[x].depth;
46+
const depthOfy: number = cache[y].depth;
47+
const parentOfx: number = cache[x].parent;
48+
const parentOfy: number = cache[y].parent;
49+
50+
return depthOfx === depthOfy && parentOfx !== parentOfy;
51+
};

0 commit comments

Comments
(0)

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