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.
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int treeHeight(TreeNode* root) { 13 if(!root) return 0; 14 15 int left_height = treeHeight(root->left); 16 if(left_height == -1) return -1; 17 int right_height = treeHeight(root->right); 18 if(right_height == -1) return -1; 19 20 if(abs(left_height-right_height) > 1) { 21 return -1; 22 } 23 else { 24 return 1 + max(left_height, right_height); 25 } 26 } 27 bool isBalanced(TreeNode *root) { 28 return treeHeight(root) != -1; 29 } 30 };