Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
The lowest common ancestor is defined as the deepest node that is an ancestor of both p and q (a node can be an ancestor of itself).
The tree is given as a level-order array where null represents missing nodes, followed by the values of nodes p and q.
For example, given tree [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], p = 5, q = 1:
3
/ \
5 1
/ \ / \
6 2 0 8
/ \
7 4
The LCA of nodes 5 and 1 is 3.
root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 13root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 45root = [1,2], p = 1, q = 21The number of nodes in the tree is in the range [2, 10^5]-10^9 <= Node.val <= 10^9All Node.val are uniquep != qp and q will exist in the treeExpected time complexity: O(n)Run your code to see results
Use Cmd+Enter to run