You are given a binary-tree root together with two nodes, p and q. Find and return their lowest common ancestor.
A lowest common ancestor is the deepest tree node for which both p and q lie in its descendant set. A node counts as its own descendant.
lowestCommonAncestor(root, p, q)
Example 1:
Input: root = [7,3,11,1,5,9,14,null,null,4,6], p = 4, q = 6
Output: 5
Explanation: Nodes 4 and 6 are both below node 5, and no node lower than 5 contains them both.
root = [7,3, 11, 1, 5, 9, 14, null, null, 4, 6] p = 4 q = 6
5
The level-order input forms this tree, with p at node 4 and q at node 6.
2 and 10^5 nodes, inclusive.p and q are present in the tree.This has been reported as LeetCode problem 236 during a software-engineer phone interview.
root = [7,3, 11, 1, 5, 9, 14, null, null, 4, 6] p = 4 q = 6
5
The level-order input forms this tree, with p at node 4 and q at node 6.