-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathBalanced_binary_tree.cpp
More file actions
67 lines (58 loc) · 2.05 KB
/
Balanced_binary_tree.cpp
File metadata and controls
67 lines (58 loc) · 2.05 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright (c) 2013 Elements of Programming Interviews. All rights reserved.
#include <algorithm>
#include <cassert>
#include <iostream>
#include <memory>
#include "./Binary_tree_prototype.h"
using std::boolalpha;
using std::cout;
using std::endl;
using std::max;
using std::unique_ptr;
int get_height(const unique_ptr<BinaryTreeNode<int>>& T);
// @include
bool is_balanced_binary_tree(const unique_ptr<BinaryTreeNode<int>>& T) {
return get_height(T) != -2;
}
int get_height(const unique_ptr<BinaryTreeNode<int>>& T) {
if (!T) {
return -1; // base case.
}
int l_height = get_height(T->left);
if (l_height == -2) {
return -2; // left subtree is not balanced.
}
int r_height = get_height(T->right);
if (r_height == -2) {
return -2; // right subtree is not balanced.
}
if (abs(l_height - r_height) > 1) {
return -2; // current node T is not balanced.
}
return max(l_height, r_height) + 1; // return the height.
}
// @exclude
int main(int argc, char* argv[]) {
// balanced binary tree test
// 3
// 2 5
// 1 4 6
unique_ptr<BinaryTreeNode<int>> root =
unique_ptr<BinaryTreeNode<int>>(new BinaryTreeNode<int>());
root->left = unique_ptr<BinaryTreeNode<int>>(new BinaryTreeNode<int>());
root->left->left = unique_ptr<BinaryTreeNode<int>>(new BinaryTreeNode<int>());
root->right = unique_ptr<BinaryTreeNode<int>>(new BinaryTreeNode<int>());
root->right->left =
unique_ptr<BinaryTreeNode<int>>(new BinaryTreeNode<int>());
root->right->right =
unique_ptr<BinaryTreeNode<int>>(new BinaryTreeNode<int>());
assert(is_balanced_binary_tree(root) == true);
cout << boolalpha << is_balanced_binary_tree(root) << endl;
// Non-balanced binary tree test.
root = unique_ptr<BinaryTreeNode<int>>(new BinaryTreeNode<int>());
root->left = unique_ptr<BinaryTreeNode<int>>(new BinaryTreeNode<int>());
root->left->left = unique_ptr<BinaryTreeNode<int>>(new BinaryTreeNode<int>());
assert(is_balanced_binary_tree(root) == false);
cout << boolalpha << is_balanced_binary_tree(root) << endl;
return 0;
}