Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C++ solution for Balanced Binary Tree #194

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions C++/balanced-binary-tree.cpp
Original file line number Diff line number Diff line change
@@ -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;
}
}
};