You are given two nodes of a binary tree p and q, return their lowest common ancestor (LCA).
Each node will have a reference to its parent node. The definition for Node is below:
class Node {
public int val;
public Node left;
public Node right;
public Node parent;
}According to the definition of LCA on Wikipedia: "The lowest common ancestor of two nodes p and q in a tree T is the lowest node that has both p and q as descendants (where we allow a node to be a descendant of itself)."
Example 1:
Input: root = [5,3,4,2,1], p = 1, q = 2
Output: 3Example 2:
Input: root = [5,3,4,2,1,null,9,null,11,10,12], p = 3, q = 12
Output: 3Constraints:
2 <= The number of nodes in the tree <= 100,000.-1,000,000,000 <= Node.val <= 1,000,000,000Node.val are unique.p != qp and q will both exist in the tree.