This commit is contained in:
parent
e1d3423ee0
commit
837812e599
11
include/s0236_lowest_common_ancestor_of_a_binary_tree.hpp
Normal file
11
include/s0236_lowest_common_ancestor_of_a_binary_tree.hpp
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
#ifndef S0236_LOWEST_COMMON_ANCESTOR_OF_A_BINARY_TREE_HPP
|
||||||
|
#define S0236_LOWEST_COMMON_ANCESTOR_OF_A_BINARY_TREE_HPP
|
||||||
|
|
||||||
|
#include "structures.hpp"
|
||||||
|
|
||||||
|
class S0236 {
|
||||||
|
public:
|
||||||
|
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q);
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif
|
17
src/s0236_lowest_common_ancestor_of_a_binary_tree.cpp
Normal file
17
src/s0236_lowest_common_ancestor_of_a_binary_tree.cpp
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
#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;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user