Determine whether a binary tree is a balanced binary tree cracking the coding interview 4.1

Source: Internet
Author: User

A balanced binary tree is defined as follows: the height difference between the left subtree of any node and the right subtree is less than or equal to 1.

Then a binary tree is a balanced binary tree and only when (1, the left subtree is a balanced binary tree, 2. the right subtree is a balanced binary tree; 3. The height difference between the left and right subtree is less than or equal to 1 ).

Therefore, if you use recursive methods to determine whether a recursive function returns two messages: balance or not, tree height. The Code is as follows.

Bool isbalance (node * proot, Int & ndeepth) {If (proot = NULL) {ndeepth = 0; return true;} int deepright; int deepleft; If (! Isbalance (proot-> pright, deepright) |! Isbalance (proot-> pleft, deepleft) return false; ndeepth = 1 + fmax (deepright, deepleft); Return ABS (deepright-deepleft) <= 1 ;}

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.