[AlgoExpert] Height Balanced Binary Tree

Height Balanced Binary Tree

  • Time : O(n)
  • Space : O(d)
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;

// This is an input class. Do not edit.
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;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/17/PS/AlgoExpert/height-balanced-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.