leetcode_question_110 Balanced Binary Tree

来源:互联网 发布:js返回顶部过渡 效果 编辑:程序博客网 时间:2024/04/29 13:57

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 everynode never differ by more than 1.

Recursive:

bool balance(TreeNode* root, int &depth)    {    if(root == NULL) {depth = 0;return true;}int leftdepth = 0;bool left = balance(root->left, leftdepth);int rightdepth = 0;bool right = balance(root->right, rightdepth);depth = leftdepth > rightdepth ? leftdepth+1 : rightdepth+1;int gap = leftdepth - rightdepth;return left && right && (-1 <= gap && gap <= 1);}bool isBalanced(TreeNode *root) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int depth = 0;return balance(root, depth);    }


原创粉丝点击