"Algorithm" How to judge a binary tree is a balanced binary tree

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.