LeetCode110 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 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.

题源:here;完整实现:here

思路:

比较二叉树左右子树的最大深度,大于1则返回false。

int maxDep(TreeNode *root){
	if (!root) return 0;
	return max(maxDep(root->left), maxDep(root->right)) + 1;
}
bool isBalanced(TreeNode* root) {
	if (!root) return true;
	if (abs(maxDep(root->left) - maxDep(root->right)) > 1)
		return false;
	return isBalanced(root->left) && isBalanced(root->right);
}

 纪念贴图:

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/81193249