From 3d90128c771bda683cb35197fd3a7e7f3e84b201 Mon Sep 17 00:00:00 2001 From: CjKostas02 Date: Thu, 3 Oct 2024 12:18:10 -0400 Subject: [PATCH] C++ solution for Balanced Binary Tree --- C++/balanced-binary-tree.cpp | 58 ++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 C++/balanced-binary-tree.cpp diff --git a/C++/balanced-binary-tree.cpp b/C++/balanced-binary-tree.cpp new file mode 100644 index 000000000..74ea9bae0 --- /dev/null +++ b/C++/balanced-binary-tree.cpp @@ -0,0 +1,58 @@ +// Time: O(n) +// Space: O(n) + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ + +class Solution { +public: + int balanceHelper(TreeNode* node, bool& balanced){ + int leftBal = 0; + int rightBal = 0; + + if(node->left != nullptr){ + leftBal = balanceHelper(node->left, balanced); + } + if(node->right != nullptr){ + rightBal = balanceHelper(node->right, balanced); + } + + if(leftBal - rightBal > 1 || leftBal - rightBal < -1){ + balanced = false; + } + + if(leftBal > rightBal){ + return 1 + leftBal; + } + else{ + return 1 + rightBal; + } + } + + + bool isBalanced(TreeNode* root) { + if(root != nullptr){ + bool balanced = true; + balanceHelper(root, balanced); + + if(!balanced){ + return false; + } + else{ + return true; + } + } + else{ + return true; + } + } +}; \ No newline at end of file