The determination of the balance binary tree of C + +---"Those strange Algorithms" __web

Source: Internet
Author: User

We know that the balanced binary tree requires that the left and right subtree of the binary tree is not more than 1, that is, the value is { -1,0,1}, while the empty tree is also a balanced binary tree, know these, we can easily carry out the balance of the binary tree, the implementation code as follows:

A function that defines the depth of a tree, we define it by recursion, and then we define a function that determines whether the tree is a balanced binary tree, also uses a recursive definition, because the left and right subtree of the balanced binary tree must be a balanced binary tree.

Class Solution {public
:
    bool isbalanced (TreeNode *root) {
        if (!root) return true; 
        else return (ABS (Depth (root->left)-depth (root->right) <2) &&isbalanced (root->left) && Isbalanced (root->right);
    }
    int depth (treenode* root) {
        if (!root) return 0;
        if (!root->left&&!root->right) return 1;
        int left=depth (root->left) +1;
        int right=depth (root->right) +1;
        Return Max (left,right);
    }
;

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.