Lowest Common Ancestor of a Binary Tree LeetCode solution in C++

1
class Solution {
2
public:
3
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
4
if (!root) {
5
return NULL;
6
}
7
if (root == p or root == q) {
8
return root;
9
}
10
TreeNode *left = lowestCommonAncestor(root->left, p, q);
11
TreeNode *right = lowestCommonAncestor(root->right, p, q);
12
if (left and right) return root;
13
if (left)
14
return left;
15
else
16
return right;
17
}
18
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0