Leetcode_110 _ Balanced Binary Tree, balancedbinarytree

Source: Internet
Author: User

Leetcode_110 _ Balanced Binary Tree, balancedbinarytree

Thank you for your reference. If you have any errors or questions, please leave a message to correct them. Thank you.

Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Calculate the height of left and right subtree and determine whether the height difference between left and right subtree cannot exceed 1.
The depth of the tree is accumulated from the root node (its depth is 1) from top to bottom layer, and the height is from the leaf node (its height is 1) accumulated from bottom to top.


/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {private:    bool balance = true;    int height(TreeNode *root)    {        if(!balance)            return -1;        if(root==NULL)            return 0;        else        {            int left_height = height(root->left)+1;            int right_height = height(root->right)+1;            if( abs(left_height-right_height) > 1)                balance = false;            else                return left_height>right_height ? left_height : right_height;        }    }public:    bool isBalanced(TreeNode *root) {        height(root);        return balance;    }};


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.