-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path1644-lowest-common-ancestor-of-a-binary-tree-ii.js
More file actions
63 lines (54 loc) · 1.63 KB
/
1644-lowest-common-ancestor-of-a-binary-tree-ii.js
File metadata and controls
63 lines (54 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* 1644. Lowest Common Ancestor of a Binary Tree II
* https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-ii/
* Difficulty: Medium
*
* Given the root of a binary tree, return the lowest common ancestor (LCA) of two given
* nodes, p and q. If either node p or q does not exist in the tree, return null. All
* values of the nodes in the tree are unique.
*
* According to the definition of LCA on Wikipedia: "The lowest common ancestor of two
* nodes p and q in a binary tree T is the lowest node that has both p and q as descendants
* (where we allow a node to be a descendant of itself)". A descendant of a node x is a
* node y that is on the path from node x to some leaf node.
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {TreeNode} p
* @param {TreeNode} q
* @return {TreeNode}
*/
var lowestCommonAncestor = function(root, p, q) {
let foundP = false;
let foundQ = false;
const lca = findLCA(root);
return foundP && foundQ ? lca : null;
function findLCA(node) {
if (!node) return null;
const leftResult = findLCA(node.left);
const rightResult = findLCA(node.right);
let currentMatch = false;
if (node === p) {
foundP = true;
currentMatch = true;
}
if (node === q) {
foundQ = true;
currentMatch = true;
}
if (leftResult && rightResult) {
return node;
}
if (currentMatch && (leftResult || rightResult)) {
return node;
}
return leftResult || rightResult || (currentMatch ? node : null);
}
};