Given the root node of a binary tree with n nodes, your task is to find the lowest common ancestor of two of its nodes, p and q.
Note: The lowest common ancestor of two nodes,
pandq, is defined as the lowest node in the binary tree that has bothpandqas descendants.A node can also be a descendant of itself. For example, if
qis a descendant ofp, and we know thatpis a descendant of itself, thenpwill be the lowest common ancestor ofpandq.
Constraints:
Node.data are unique.p != qp and q exist in the tree.Start from the root and recursively search the left and right subtrees. At each node, check if it matches either of the two given nodes. If it does, return that node since it’s a potential ancestor. Otherwise, continue searching for the nodes in both subtrees. As the recursion explores the left and right subtrees, it returns a node if one of the given nodes is found or returns null if neither node is found in that subtree.
At each node, if only one of the subtrees returns a non-null result, it means both nodes are located in that subtree. The non-null result propagates upwards as you search for the lowest common ancestor.
If both ...
Given the root node of a binary tree with n nodes, your task is to find the lowest common ancestor of two of its nodes, p and q.
Note: The lowest common ancestor of two nodes,
pandq, is defined as the lowest node in the binary tree that has bothpandqas descendants.A node can also be a descendant of itself. For example, if
qis a descendant ofp, and we know thatpis a descendant of itself, thenpwill be the lowest common ancestor ofpandq.
Constraints:
Node.data are unique.p != qp and q exist in the tree.Start from the root and recursively search the left and right subtrees. At each node, check if it matches either of the two given nodes. If it does, return that node since it’s a potential ancestor. Otherwise, continue searching for the nodes in both subtrees. As the recursion explores the left and right subtrees, it returns a node if one of the given nodes is found or returns null if neither node is found in that subtree.
At each node, if only one of the subtrees returns a non-null result, it means both nodes are located in that subtree. The non-null result propagates upwards as you search for the lowest common ancestor.
If both ...