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 everynode never differ by more than 1.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isBalancedNew(TreeNode *root, int & height){ if (!root){ height = 0; return true; } int left_height = 0, right_height = 0; bool left_flag = isBalancedNew(root->left,left_height); bool right_flag = isBalancedNew(root->right,right_height); height = max(left_height,right_height) + 1; return left_flag && right_flag && abs(left_height - right_height) <= 1; } bool isBalanced(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function int height = 0; return isBalancedNew(root,height); } };