Leetcode/cpp/110.cpp
2024-06-21 01:36:27 +01:00

27 lines
848 B
C++

// https://leetcode.com/problems/balanced-binary-tree/submissions/1292988627/
/**
* Definition for a binary tree node.
*/
#include <algorithm>
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:
bool isBalanced(TreeNode* root) {
if (root == nullptr) return true;
return std::abs(height(root->left) - height(root->right)) < 2 && isBalanced(root->left) && isBalanced(root->right);
}
int height(TreeNode* root) {
if (root == nullptr) return 0;
return (root->val = 1 + std::max(height(root->left), height(root->right)));
}
};