Height Balanced Binary Tree
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| using namespace std;
class BinaryTree { public: int value; BinaryTree *left = nullptr; BinaryTree *right = nullptr;
BinaryTree(int value) { this->value = value; } };
pair<bool, int> helper(BinaryTree* tree, int depth = 0) { if(!tree) return {true, depth}; auto [lb, ld] = helper(tree->left, depth + 1); if(!lb) return {false, -1}; auto [rb, rd] = helper(tree->right, depth + 1); if(!rb) return {false, -1}; int mi = min(ld, rd); int ma = max(ld, rd); if(ma - mi > 1) return {false, -1}; return {true, ma}; }
bool heightBalancedBinaryTree(BinaryTree *tree) { return helper(tree).first; }
|