Given the root of a binary tree and an array of TreeNode objects nodes, return the lowest common ancestor (LCA) of all the nodes in nodes. All the nodes will exist in the tree, and all values of the tree's nodes are unique.
Extending the definition of LCA on Wikipedia: "The lowest common ancestor of n nodes p1, p2, ..., pn in a binary tree T is the lowest node that has every pi as a descendant (where we allow a node to be a descendant of itself) for every valid i". A descendant of a node x is a node y that is on the path from node x to some leaf node.
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [4,7] Output: 2 Explanation: The lowest common ancestor of nodes 4 and 7 is node 2.
Example 2:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [1] Output: 1 Explanation: The lowest common ancestor of a single node is the node itself.
Example 3:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [7,6,2,4] Output: 5 Explanation: The lowest common ancestor of the nodes 7, 6, 2, and 4 is node 5.
Constraints:
[1, 104].-109 <= Node.val <= 109Node.val are unique.nodes[i] will exist in the tree.nodes[i] are distinct.We use a hash table s to record the values of all nodes in the array nodes, and then use depth-first search. When the node being traversed is null or its value is in the hash table s, we return the current node. Otherwise, we recursively traverse the left and right subtrees. If the return values of both the left and right subtrees are not null, it means the current node is the lowest common ancestor. Otherwise, we return the non-null subtree's return value.
The time complexity is O(n + m), and the space complexity is O(n + m). Where n and m are the number of nodes in the binary tree and the length of the array nodes, respectively.
Java
C++
JavaScript
Lowest Common Ancestor of a Binary Search Tree - Leetcode 235 - Python • NeetCode • 274,690 views views
Watch 9 more video solutions →Practice Lowest Common Ancestor of a Binary Tree IV with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor