Balanced Binary Tree

来源:互联网 发布:安卓手机变win7软件 编辑:程序博客网 时间:2024/06/18 16:29

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.


class Solution {public:    bool is_balanced = true;    int checkHieght(TreeNode *root) {        int lh = 0, rh = 0;        if(root == NULL || is_balanced == false) return 0;        if(root->left != NULL && is_balanced == true)             lh = checkHieght(root->left) + 1;        if(root->right != NULL && is_balanced == true)             rh = checkHieght(root->right) + 1;        if(abs(lh - rh) > 1) is_balanced = false;        return lh > rh ? lh : rh;    }    bool isBalanced(TreeNode *root) {        checkHieght(root);        return is_balanced;    }};


0 0
原创粉丝点击