Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Binary tree balanced or not
#include <iostream> #include <list> #include <vector> using namespace std; struct BinTree { int data; BinTree *left; BinTree *right; BinTree(int d, BinTree* l, BinTree* r): data(d), left(l), right(r) {} }; int balanced(BinTree* root) { if (!root) return 0; int lHeight = balanced(root->left); int rHeight = balanced(root->right); if (lHeight == -1 || rHeight == -1) return -1; if (abs(lHeight - rHeight) > 1) return -1; return 1 + max(lHeight, rHeight); } bool isBalanced(BinTree* root) { if (balanced(root) == -1) return false; return true; } // 4 // / \ // 2 8 // / \ / \ // 1 3 6 9 // / \ // 5 7 // / // 11 // / // 12 // int main() { BinTree *l = new BinTree(12, NULL, NULL); BinTree *k = new BinTree(11, NULL, NULL); BinTree *h = new BinTree(7, NULL, NULL); BinTree *j = new BinTree(5, NULL, NULL); BinTree *g = new BinTree(9, NULL, NULL); BinTree *f = new BinTree(6, j, h); BinTree *e = new BinTree(3, NULL, NULL); BinTree *d = new BinTree(1, NULL, NULL); BinTree *c = new BinTree(8, f, g); BinTree *b = new BinTree(2, d, e); BinTree *a = new BinTree(4, b, c); cout << boolalpha << isBalanced(a); }
run
|
edit
|
history
|
help
0
threadpool01
Вариант универсального указателя.
NonparaSign
Palindromo
Why C++ optimizer has problems with these temporary variables
st_match
Graph Theory 2
Conjuntos - Contar caracteres únicos
spiral traversal of a matrix
Anagrams WIP