318. Lowest Common Ancestor of a Binary Tree III

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 is below

class TreeNode {

public int val;

public TreeNode left;

public TreeNode right;

public TreeNode parent;

}

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 = [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 since a node can be a descendant of itself according to the LCA definition.

Now Your Turn!

Pick the correct output for the given input

Input: root = [1,2], p = 1, q = 2

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 [2, 105].
  • -109 <= Node.val <= 109
  • All Node.val are unique.
  • p != q
  • p and q exist in the tree.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/*
// Definition for a Node.
class TreeNode {
public:
int data;
TreeNode* left;
TreeNode* right;
TreeNode* parent;
};
*/
 
 
 
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* p, TreeNode* q) {
}
};
 
Test Case

Input:

P
Q
Root