My first Leetcode code.
/**
* Definition for a binary tree node.
* struct TreeNode {
*? ? int val;
*? ? TreeNode *left;
*? ? TreeNode *right;
*? ? TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#define max(val1, val2)? (val1 > val2 ? val1 : val2)
#define min(val1, val2)? (val1 < val2 ? val1 : val2)
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == nullptr || p == nullptr || q == nullptr ) return nullptr;
if (max(p->val, q->val) < root->val)
return lowestCommonAncestor(root->left, p, q);
else if (min(p->val, q->val) > root->val)
return lowestCommonAncestor(root->right, p, q);
else
return root;
}
};