第47天。
今天的题目是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.
题目意思是对这个树的每个结点来说它左子树和右子树的高度差都不大于1,我们可以把它转换成一个求高度的问题:
bool isBalanced ( TreeNode * root ) {
return isBalanced ( root , h );
bool isBalanced ( TreeNode * root , int & height ) {
if ( root == nullptr ) { height = 0 ; return true ; }
if ( ! isBalanced ( root -> left , left ) || ! isBalanced ( root -> right , right ))
if ( abs ( left - right ) > 1 ) return false ;
height = max ( left , right ) + 1 ;
准备把主力语言往python
和c
上靠,所以以后都会写多一个python
的解法。
def isBalanced ( self , root ):
res , height = self . isBalancedRec ( root )
def isBalancedRec ( self , root ):
leftRes , leftH = self . isBalancedRec ( root . left )
rightRes , rightH = self . isBalancedRec ( root . right )
if leftRes == False or rightRes == False :
return False , max ( leftH , rightH )
return abs ( leftH - rightH ) <= 1 , max ( leftH , rightH ) + 1