title : How to judge a binary tree is a balanced binary tree
definition :
Balanced binary tree (AVL): 1, empty binary tree is AVL tree;
2, if T is a non-empty two-fork search tree, TL and TR respectively is its Saozi right subtree, then when T satisfies the condition, T is an AVL tree: (1) TL and TR are AVL trees; (2) | Hl-hr| "=1,hl and HR are the heights of the Saozi right subtree, respectively.
Example :
algorithm Idea :
Recursive calls are made from the root node using recursive thinking. Assuming that the height of the leaf node is 0, the height difference of the left and right sub-trees of each node is calculated respectively, and if the height difference is greater than 1 returns-1 (indicates not the balance tree) otherwise returns the maximum height of the subtree plus one.
Complexity of Time :
T (root) = T (left) + t (right) + O (1)
= t (m->left) + t (m->right) + t (...) + O (1) ...
= ... O (1) + O (1) = N*o (1) = O (n)
Code Implementation :
Bool isbalanced (node* root) {
return height (root) >= 0;
}
Int height (node* root) {
if (root = null) return 0;
int Left = height (root-left);
int Right = height (root-right);
if (ABS (left,right) >1 | | | < 0 | | Right < 0)
return-1;
Else
return Max (left, right) + 1;
}
Attached: Algorithm for tree general time complexity is O (log2 N) or O (n)
"Algorithm" How to judge a binary tree is a balanced binary tree