Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e3dd2de

Browse files
solves lowest common ancestor of binary tree
1 parent 43ebf23 commit e3dd2de

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@
190190
| 232 | [Implement Queue Using Stacks](https://leetcode.com/problems/implement-queue-using-stacks) | [![Java](assets/java.png)](src/MyQueue.java) [![Python](assets/python.png)](python/implement_queue_using_stacks.py) | |
191191
| 234 | [Palindrome Linked Lists](https://leetcode.com/problems/palindrome-linked-list) | [![Java](assets/java.png)](src/PalindromeLinkedList.java) [![Python](assets/python.png)](python/palindrome_linked_list.py) | |
192192
| 235 | [Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree) | [![Java](assets/java.png)](src/LowestCommonAncestorOfBinarySearchTree.java) [![Python](assets/python.png)](python/lowest_common_ancestor_of_bst.py) | |
193-
| 236 | [Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree) | | |
193+
| 236 | [Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree) | [![Java](assets/java.png)](src/LowestCommonAncestorOfBinaryTree.java) | |
194194
| 237 | [Delete a Node In A Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list) | [![Java](assets/java.png)](src/DeleteANodeInLinkedList.java) [![Python](assets/python.png)](python/delete_node_in_linked_list.py) | |
195195
| 238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self) | | |
196196
| 240 | [Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii) | | |
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree
2+
// T: O(N)
3+
// S: O(log(N))
4+
5+
public class LowestCommonAncestorOfBinaryTree {
6+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
7+
if (root == null || root == p || root == q) return root;
8+
TreeNode left = lowestCommonAncestor(root.left, p, q);
9+
TreeNode right = lowestCommonAncestor(root.right, p, q);
10+
if (left != null && right != null) return root;
11+
return left == null ? right : left;
12+
}
13+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /