From 495a134494230166f20321dbc754b8464a6586ab Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Tue, 31 Jan 2023 11:19:09 +0800 Subject: [PATCH] s0110 --- include/s0110_balanced_binary_tree.hpp | 15 +++++++++++++++ src/s0110_balanced_binary_tree.cpp | 17 +++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 include/s0110_balanced_binary_tree.hpp create mode 100644 src/s0110_balanced_binary_tree.cpp diff --git a/include/s0110_balanced_binary_tree.hpp b/include/s0110_balanced_binary_tree.hpp new file mode 100644 index 0000000..184079f --- /dev/null +++ b/include/s0110_balanced_binary_tree.hpp @@ -0,0 +1,15 @@ +#ifndef S0110_BALANCED_BINARY_TREE_HPP +#define S0110_BALANCED_BINARY_TREE_HPP + +#include + +#include "structures.hpp" + +using namespace std; + +class S0110 { + public: + bool isBalanced(TreeNode* root); +}; + +#endif diff --git a/src/s0110_balanced_binary_tree.cpp b/src/s0110_balanced_binary_tree.cpp new file mode 100644 index 0000000..db11144 --- /dev/null +++ b/src/s0110_balanced_binary_tree.cpp @@ -0,0 +1,17 @@ +#include "s0110_balanced_binary_tree.hpp" + +struct Info { + bool isBalanced; + int depth; +}; + +Info getInfo(TreeNode* root) { + if (root == nullptr) return Info{true, 0}; + Info left = getInfo(root->left); + Info right = getInfo(root->right); + return Info{ + left.isBalanced && right.isBalanced && abs(left.depth - right.depth) <= 1, + max(left.depth, right.depth) + 1}; +} + +bool S0110::isBalanced(TreeNode* root) { return getInfo(root).isBalanced; }