Skip to content

Commit 17b9b91

Browse files
authored
Update 1676-lowest-common-ancestor-of-a-binary-tree-iv.js
1 parent a736e69 commit 17b9b91

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

1676-lowest-common-ancestor-of-a-binary-tree-iv.js

+29
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,32 @@ const lowestCommonAncestor = function(root, nodes) {
2020
if(left && right) return root
2121
return left ? left : right
2222
};
23+
24+
// another
25+
26+
/**
27+
* Definition for a binary tree node.
28+
* function TreeNode(val) {
29+
* this.val = val;
30+
* this.left = this.right = null;
31+
* }
32+
*/
33+
/**
34+
* @param {TreeNode} root
35+
* @param {TreeNode[]} nodes
36+
* @return {TreeNode}
37+
*/
38+
const lowestCommonAncestor = function(root, nodes) {
39+
const set = new Set(nodes)
40+
return dfs(root)
41+
42+
function dfs(node) {
43+
if(node == null) return node
44+
const left = dfs(node.left)
45+
const right = dfs(node.right)
46+
47+
if(set.has(node)) return node
48+
if(left && right) return node
49+
return left || right
50+
}
51+
};

0 commit comments

Comments
 (0)