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 everynode 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,那么我們肯定需要一個求各個點深度的函數,然后對每個節點的兩個子樹來比較深度差,時間復雜度為O(NlgN),代碼如下:
解法一:
class Solution { public: bool isBalanced(TreeNode *root) { if (!root) return true; if (abs(getDepth(root->left) - getDepth(root->right)) > 1) return false; return isBalanced(root->left) && isBalanced(root->right); } int getDepth(TreeNode *root) { if (!root) return 0; return 1 + max(getDepth(root->left), getDepth(root->right)); } };
上面那個方法正確但不是很高效,因為每一個點都會被上面的點計算深度時訪問一次,我們可以進行優化。方法是如果我們發現子樹不平衡,則不計算具體的深度,而是直接返回-1。那么優化后的方法為:對於每一個節點,我們通過checkDepth方法遞歸獲得左右子樹的深度,如果子樹是平衡的,則返回真實的深度,若不平衡,直接返回-1,此方法時間復雜度O(N),空間復雜度O(H),參見代碼如下:
解法二:
class Solution { public: bool isBalanced(TreeNode *root) { if (checkDepth(root) == -1) return false; else return true; } int checkDepth(TreeNode *root) { if (!root) return 0; int left = checkDepth(root->left); if (left == -1) return -1; int right = checkDepth(root->right); if (right == -1) return -1; int diff = abs(left - right); if (diff > 1) return -1; else return 1 + max(left, right); } };
類似題目:
參考資料:
https://leetcode.com/problems/balanced-binary-tree/