Skip to content

Commit 2b5927b

Browse files
committed
Add solution #236
1 parent 7ddb65a commit 2b5927b

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,7 @@
206206
232|[Implement Queue using Stacks](./0232-implement-queue-using-stacks.js)|Easy|
207207
234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy|
208208
235|[Lowest Common Ancestor of a Binary Search Tree](./0235-lowest-common-ancestor-of-a-binary-search-tree.js)|Easy|
209+
236|[Lowest Common Ancestor of a Binary Tree](./0236-lowest-common-ancestor-of-a-binary-tree.js)|Medium|
209210
237|[Delete Node in a Linked List](./0237-delete-node-in-a-linked-list.js)|Easy|
210211
238|[Product of Array Except Self](./0238-product-of-array-except-self.js)|Medium|
211212
242|[Valid Anagram](./0242-valid-anagram.js)|Easy|
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* 236. Lowest Common Ancestor of a Binary Tree
3+
* https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
4+
* Difficulty: Medium
5+
*
6+
* Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
7+
*
8+
* According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined
9+
* between two nodes p and q as the lowest node in T that has both p and q as descendants
10+
* (where we allow a node to be a descendant of itself).”
11+
*/
12+
13+
/**
14+
* Definition for a binary tree node.
15+
* function TreeNode(val) {
16+
* this.val = val;
17+
* this.left = this.right = null;
18+
* }
19+
*/
20+
/**
21+
* @param {TreeNode} root
22+
* @param {TreeNode} p
23+
* @param {TreeNode} q
24+
* @return {TreeNode}
25+
*/
26+
var lowestCommonAncestor = function(root, p, q) {
27+
if (!root || root === p || root === q) return root;
28+
const [l, r] = [lowestCommonAncestor(root.left, p, q), lowestCommonAncestor(root.right, p, q)];
29+
return l && r ? root : l ?? r;
30+
};

0 commit comments

Comments
 (0)