Given a binary tree, determine whether it is a highly balanced binary tree.
In this problem, a height-balanced binary tree is defined as:
The absolute value of the height difference between the left and right subtrees of each node of a binary tree does not exceed 1.
Example 1:
Given a binary tree [3,9,20,null,null,15,7]
3 / \ 9 20 / \ 15 7
return true
.
Example 2:
Given a binary tree [1,2,2,3,3,null,null,4,4]
1 / \ 2 2 / \ 3 3 / \ 4 4
return false
.
1 /** 2 * Definition for a binary tree node. 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 getHeight(TreeNode* root){ 13 if(root == NULL) return 0; 14 int l = getHeight(root->left); 15 int r = getHeight(root->right); 16 return l > r ? l+1 : r+1; 17 } 18 bool isBalanced(TreeNode* root) { 19 if(root == NULL) return true; 20 if(getHeight(root->left) - getHeight(root->right) > 1) return false; 21 else if(getHeight(root->right) - getHeight(root->left) > 1) return false; 22 else return isBalanced(root->left) && isBalanced(root->right); 23 } 24 };