From 837812e5994c7ae6ade285e103aed51931fb1adb Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Tue, 31 Jan 2023 16:08:05 +0800 Subject: [PATCH] s0236 --- ..._lowest_common_ancestor_of_a_binary_tree.hpp | 11 +++++++++++ ..._lowest_common_ancestor_of_a_binary_tree.cpp | 17 +++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 include/s0236_lowest_common_ancestor_of_a_binary_tree.hpp create mode 100644 src/s0236_lowest_common_ancestor_of_a_binary_tree.cpp diff --git a/include/s0236_lowest_common_ancestor_of_a_binary_tree.hpp b/include/s0236_lowest_common_ancestor_of_a_binary_tree.hpp new file mode 100644 index 0000000..3ec4f6a --- /dev/null +++ b/include/s0236_lowest_common_ancestor_of_a_binary_tree.hpp @@ -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 diff --git a/src/s0236_lowest_common_ancestor_of_a_binary_tree.cpp b/src/s0236_lowest_common_ancestor_of_a_binary_tree.cpp new file mode 100644 index 0000000..734f3e9 --- /dev/null +++ b/src/s0236_lowest_common_ancestor_of_a_binary_tree.cpp @@ -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; + } +}