Skip to content

Commit a5b2cee

Browse files
authored
Create 1506-find-root-of-n-ary-tree.js
1 parent aeb0595 commit a5b2cee

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

1506-find-root-of-n-ary-tree.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* // Definition for a Node.
3+
* function Node(val, children) {
4+
* this.val = val === undefined ? 0 : val;
5+
* this.children = children === undefined ? [] : children;
6+
* };
7+
*/
8+
9+
/**
10+
* @param {Node[]} tree
11+
* @return {Node}
12+
*/
13+
const findRoot = function(tree) {
14+
let sum = 0
15+
for(let n of tree) {
16+
sum += n.val
17+
for(let c of n.children) {
18+
sum -= c.val
19+
}
20+
}
21+
for(let n of tree) {
22+
if(n.val === sum) return n
23+
}
24+
return null
25+
};

0 commit comments

Comments
 (0)