You are given two nodes, p and q. The task is to return their lowest common ancestor (LCA). Both nodes have a reference to their parent node. The tree’s root is not provided; you must use the parent pointers to find the nodes’ common ancestor.
Note: The lowest common ancestor of two nodes,
pandq, is the lowest node in the binary tree, with bothpandqas descendants.In a tree, a descendant of a node is any node reachable by following edges downward from that node, including the node itself.
Constraints:
Node.data
The number of nodes in the tree is in the range
All Node.data are unique.
p != q
Both p and q are present in the tree.
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Which statement best describes the lowest common ancestor (LCA) of two nodes in a binary tree?
The node with the highest value is an ancestor of both nodes.
The node with the lowest value is an ancestor of both nodes.
The lowest common ancestor of two nodes in a binary tree is the deepest node that is an ancestor of both nodes.
The shallowest node is an ancestor of both nodes.
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding on how to solve this problem.
Implement your solution in the following coding playground.
You are given two nodes, p and q. The task is to return their lowest common ancestor (LCA). Both nodes have a reference to their parent node. The tree’s root is not provided; you must use the parent pointers to find the nodes’ common ancestor.
Note: The lowest common ancestor of two nodes,
pandq, is the lowest node in the binary tree, with bothpandqas descendants.In a tree, a descendant of a node is any node reachable by following edges downward from that node, including the node itself.
Constraints:
Node.data
The number of nodes in the tree is in the range
All Node.data are unique.
p != q
Both p and q are present in the tree.
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Which statement best describes the lowest common ancestor (LCA) of two nodes in a binary tree?
The node with the highest value is an ancestor of both nodes.
The node with the lowest value is an ancestor of both nodes.
The lowest common ancestor of two nodes in a binary tree is the deepest node that is an ancestor of both nodes.
The shallowest node is an ancestor of both nodes.
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding on how to solve this problem.
Implement your solution in the following coding playground.