1. 題目描述
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.
2. 分析
根據平衡二叉樹(BST)的定義:給出一棵樹的根節點,讓我們判斷這棵樹是不是滿足平衡二叉樹的條件:即任意一個節點的左右子樹的深度之差不大於1.
拿到題目,我的第一反應就是先設計一個求樹的深度的函數,然後再對整棵樹進行遞歸遍歷,判斷每個節點下面的左右子樹深度之差,如果大於1的話,則爲false。用了9ms過了226個測試樣例,如下:
3. 源碼
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int getDepth(TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftDepth = getDepth(root->left);
int rightDepth = getDepth(root->right);
if (leftDepth > rightDepth) {
return leftDepth+1;
}
return rightDepth+1;
}
bool isBalanced(TreeNode* root) {
if (root == NULL) {
return true;
}
int leftDepth = getDepth(root->left);
int rightDepth = getDepth(root->right);
if (abs(leftDepth - rightDepth) <= 1) {
if(isBalanced(root->left) == true && isBalanced(root->right) == true) {
return true;
}
return false;
}
return false;
}
};
4. 心得
這是BST比較基礎的題目,但是在做的時候還是交了3次纔得到正確結果。2次失敗的原因是:
4.1. 第1次失敗
沒有通過樣例[1,2,2,3,null,null,3,4,null,null,4],這是因爲我只考慮了根節點左右子樹深度之差滿足條件,而忘記了每一個節點都需要。
4.2. 第2次失敗
沒有通過樣例[1,2,3,4,5,null,6,7,null,null,null,null,8],這是因爲在設計返回值條件的時候只遍歷了左子樹,沒有遍歷右子樹的情況。