题目描述:
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.
Example 1:
Given the following tree [3,9,20,null,null,15,7]
:
3 / \ 9 20 / \ 15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]
:
1 / \ 2 2 / \ 3 3 / \ 4 4
Return false.
检测一个二叉树是不是二叉平衡树,二叉平衡树的性质是:每个分支的深度相差不超过1。
解题思路:
这题可以用递归求解:返回节点两个分支的深度,比较这两个分支深度相差是否大于1,是的话返回-1,不是则返回最大深度(若两个分支深度中有-1,直接返回-1)。代码基本和求二叉树最大深度一样,只是多了一道比较深度的步骤。
代码:
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 checkBalanced(TreeNode* root){ 13 if(!root) 14 return 0; 15 int left=checkBalanced(root->left),right=checkBalanced(root->right); 16 if(left==-1||right==-1||abs(right-left)>1) 17 return -1; 18 return max(left,right)+1; 19 } 20 bool isBalanced(TreeNode* root) { 21 if(checkBalanced(root)==-1) 22 return false; 23 else 24 return true; 25 } 26 };