leetcode/src/s0236_lowest_common_ancesto...

18 lines
563 B
C++

#include "s0236_lowest_common_ancestor_of_a_binary_tree.hpp"
TreeNode* S0236::lowestCommonAncestor(TreeNode* root, TreeNode* p,
TreeNode* q) {
if (root == nullptr || root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left != nullptr && right != nullptr) {
return root;
} else if (left != nullptr) {
return left;
} else if (right != nullptr) {
return right;
} else {
return nullptr;
}
}