1. 程式人生 > >【LeetCode & 劍指offer刷題】樹題5:110 Balanced Binary Tree

【LeetCode & 劍指offer刷題】樹題5:110 Balanced Binary Tree

【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 of
  every   node never differ by more than 1.
Example 1: Given the following tree   [3,9,20,null,null,15,7] : Return true.   Example 2:
Given the following tree   [1,2,2,3,3,null,null,4,4] : Return false.   /**  * Definition for a binary tree node.  * struct TreeNode {
 *     int val;  *     TreeNode *left;  *     TreeNode *right;  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}  * };  */   /* 對於每一個節點,我們通過 checkDepth 方法遞迴獲得左右子樹的深度, 如果子樹是平衡的,則返回真實的深度,若不平衡,直接返回 -1 此方法時間複雜度 O(N) ,空間複雜度 O(H)   對於用遞迴求解的題,可以畫遞迴樹來分析 */ class Solution { public :         bool isBalanced ( TreeNode * root )     {         if ( checkDepth ( root ) == - 1 ) return false ;         else return true ;     }         //類似問題:104. Maximum Depth of Binary Tree
    int checkDepth ( TreeNode * root )     {         if (! root ) return 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 );     } };