【LeetCode & 劍指offer刷題】樹題5:110 Balanced Binary Tree
阿新 • • 發佈:2019-01-05
【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)
110. 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 ofExample 1: Given the following tree [3,9,20,null,null,15,7] :every node never differ by more than 1.
![](110.%20Balanced%20Binary%20Tree_files/Image.png)
![](110.%20Balanced%20Binary%20Tree_files/Image%20[1].png)
int checkDepth ( TreeNode * root ) { if (! root ) return 0 ; // 為空時,返回深度 0 int left = checkDepth ( root -> left ); // 返回左子樹的深度,如果不平衡,返回 -1 if ( left == - 1 ) return - 1 ; //只要哪裡有-1一路返回,直到遞迴結束 int right = checkDepth ( root -> right ); // 返回右子樹的深度 if ( right == - 1 ) return - 1 ; int diff = abs ( left - right ); // 計算左右子樹的深度差,如果不平衡,返回 -1 ,平衡則返回實際深度 if ( diff > 1 ) return - 1 ; else return 1 + max ( left , right ); } };