balanced-binary-tree

来源:互联网 发布:mysql导入sql文件命令 编辑:程序博客网 时间:2024/06/17 21:44

题目:

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:    int depth(TreeNode *root){        if (root == NULL)            return 0;        int leftDepth = depth(root->left);        int rightDepth = depth(root->right);        return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;    }    bool isBalanced(TreeNode *root) {        if (root == NULL)            return true;        int diffDepth = depth(root->left) - depth(root->right);        if (diffDepth >= -1 && diffDepth <= 1){            return (isBalanced(root->left) && isBalanced(root->right));        }        else{            return false;        }    }};