-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path236. Lowest Common Ancestor of a Binary Tree.cpp
39 lines (34 loc) · 1.27 KB
/
236. Lowest Common Ancestor of a Binary Tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//DAY 9 PROBLEM 2
//using recursion, the idea is to keep track of the left and the right search values while performing the inorder traversal.If the root equals to any of the two nodes given,
//return the node otherwise return NULL to the values of left search and right search.
//If the values of left search and right search, both are non-null, then we got our ans else we keep returning the non-null values upwards
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL)
return NULL;
if(root==p||root==q)
return root;
TreeNode* leftNode=NULL;
TreeNode* rightNode=NULL;
leftNode=lowestCommonAncestor(root->left,p,q);
rightNode=lowestCommonAncestor(root->right,p,q);
if(leftNode&&rightNode)
return root;
else if(leftNode==NULL&&rightNode==NULL)
return NULL;
else if(leftNode||rightNode)
return leftNode?leftNode:rightNode;
else
return NULL;
}
};