File tree Expand file tree Collapse file tree 2 files changed +52
-0
lines changed Expand file tree Collapse file tree 2 files changed +52
-0
lines changed Original file line number Diff line number Diff line change 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 :
Original file line number Diff line number Diff line change 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+ } ;
You can’t perform that action at this time.
0 commit comments