383. Lowest Common Ancestor of a Binary Tree II

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes p and q. If either p or q does not exist in the tree, return null.

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1

Output: 3

Explanation:

The LCA of nodes 5 and 1 is 3.

Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4

Output: 5

Explanation:

The LCA of nodes 5 and 4 is 5.

Now Your Turn!

Pick the correct output for the given input

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 9

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • The number of nodes in the tree is in the range [1, 104]
  • -10⁹ ≤ Node.val ≤ 10⁹
  • All Node.val are unique.
  • p ≠ q

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* Definition for a binary tree node.
* class TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : data(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
//Your Code Goes Here
}
};
Test Case

Input:

P
Q
Root