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

Update 0110-balanced-binary-tree.cpp #3575

Open
wants to merge 1 commit into
base: main
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
49 changes: 31 additions & 18 deletions cpp/0110-balanced-binary-tree.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,27 +21,40 @@
class Solution {
public:
bool isBalanced(TreeNode* root) {
int height = 0;
return dfs(root, height);
return dfs(root).first;
}
// bool isBalanced(TreeNode* root) {
// int height = 0;
// return dfs(root, height);
// }

private:
bool dfs(TreeNode* root, int& height) {
if (root == NULL) {
height = -1;
return true;
}
pair<bool, int> dfs(TreeNode* root) {
if (!root) return {true, 0};

auto left = dfs(root->left);
auto right = dfs(root->right);

bool balanced = left.first && right.first && abs(left.second - right.second) <= 1;
return {balanced, 1 + max(left.second, right.second)};
}
// bool dfs(TreeNode* root, int& height) {
// if (root == NULL) {
// height = -1;
// return true;
// }

int left = 0;
int right = 0;
// int left = 0;
// int right = 0;

if (!dfs(root->left, left) || !dfs(root->right, right)) {
return false;
}
if (abs(left - right) > 1) {
return false;
}
// if (!dfs(root->left, left) || !dfs(root->right, right)) {
// return false;
// }
// if (abs(left - right) > 1) {
// return false;
// }

height = 1 + max(left, right);
return true;
}
// height = 1 + max(left, right);
// return true;
// }
};