diff --git a/README.md b/README.md index 041058e..ab2288a 100644 --- a/README.md +++ b/README.md @@ -683,7 +683,7 @@ | [Swift](./Array/SlidingWindowMaximum.swift) | 239 | [Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/) | Hard | | [Swift](./Array/ProductExceptSelf.swift) | 238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | Medium | | | 237 | [Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/) | Easy | -| | 236 | [Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/) | Medium | +| [Swift](./Tree/LowestCommonAncestorBinaryTree.swift) | 236 | [Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/) | Medium | | [Swift](./Tree/LowestCommonAncestorBinarySearchTree.swift) | 235 | [Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/) | Easy | | [Swift](./LinkedList/PalindromeLinkedList.swift) | 234 | [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/) | Easy | | | 233 | [Number of Digit One](https://leetcode.com/problems/number-of-digit-one/) | Hard | diff --git a/Tree/LowestCommonAncestorBinaryTree.swift.swift b/Tree/LowestCommonAncestorBinaryTree.swift.swift new file mode 100644 index 0000000..691727a --- /dev/null +++ b/Tree/LowestCommonAncestorBinaryTree.swift.swift @@ -0,0 +1,32 @@ +/** + * Question Link: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ + * Primary idea: Bottoms up traversal and compare root with p and q + * Time Complexity: O(n), Space Complexity: O(1) + * + * Definition for a binary tree node. + * public class TreeNode { + * public var val: Int + * public var left: TreeNode? + * public var right: TreeNode? + * public init(_ val: Int) { + * self.val = val + * self.left = nil + * self.right = nil + * } + * } + */ + +class LowestCommonAncestorBinaryTree { + func lowestCommonAncestor(_ root: TreeNode?, _ p: TreeNode?, _ q: TreeNode?) -> TreeNode? { + guard let root = root else { return nil } + if root === p || root === q { + return root + } + let leftNode = lowestCommonAncestor(root.left, p, q) + let rightNode = lowestCommonAncestor(root.right, p, q) + if leftNode != nil, rightNode != nil { + return root + } + return leftNode ?? rightNode + } +}