Lowest Common Ancestor in a Parent Tree
Problem statement
A rooted tree with nodes 0 through n - 1 is represented by parent. The root is node 0, parent[0] = -1, and for every other node i, parent[i] is its direct parent.
Given nodes p and q, return their lowest common ancestor: the common ancestor farthest from the root. A node is an ancestor of itself.
Function
lowestCommonAncestor(parent: int[], p: int, q: int) → intExamples
Example 1
parent = [-1,0,0,1,1,2,2]p = 3q = 4return = 1Nodes 3 and 4 are both direct children of node 1.
Example 2
parent = [-1,0,0,1,1,2,2]p = 3q = 6return = 0The two nodes lie in different root subtrees.
Constraints
1 <= parent.length <= 100000.parent[0] = -1.- For
i > 0,0 <= parent[i] < i. 0 <= p, q < parent.length.