Skip to content

Commit d2727b7

Browse files
authored
Create main.cpp
1 parent 76514f0 commit d2727b7

File tree

1 file changed

+25
-0
lines changed
  • 17 - Binary Tree Data Structure Problems/26 - Lowest Common Ancestor of a Binary Tree

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
13+
if(root == NULL) return NULL;
14+
15+
if(root -> val == p -> val || root -> val == q -> val) return root;
16+
17+
TreeNode* leftAns = lowestCommonAncestor(root -> left, p, q);
18+
TreeNode* rightAns = lowestCommonAncestor(root -> right, p, q);
19+
20+
if(leftAns != NULL && rightAns != NULL) return root;
21+
else if(leftAns != NULL && rightAns == NULL) return leftAns;
22+
else if(leftAns == NULL && rightAns != NULL) return rightAns;
23+
else return NULL;
24+
}
25+
};

0 commit comments

Comments
 (0)