題目:
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(下面給出兩種代碼實現,代碼1和代碼2):採用遞歸的方法,對每一層的節點進行遍歷,從葉子節點開始回溯,並從下往上判斷每一層的各個是否滿足平衡樹的條件,並得到以該節點爲根節點的左右子樹的深度,進而得到該節點的深度以便於上層的判決。代碼1:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode *root) {
if(!root)return true;
int depth;
return CheckBal(root,&depth);
}
private:
bool CheckBal(TreeNode *root, int *depth){
if(root==nullptr){
*depth=0;
return true;
}
int depth_left=0,depth_right=0;
if(!CheckBal(root->left,&depth_left)||!CheckBal(root->right,&depth_right)||abs(depth_left-depth_right)>1){
return false;
}
*depth=max(depth_left,depth_right)+1;
return true;
}
};
代碼2:這段代碼是我一開始寫的代碼,看起來要長不少。因爲代碼中有一個問題——將左右子樹作爲兩個參數傳入函數中,導致函數在運行時需要對左右兩顆子樹分別作處理,其實可以歸併爲同一段代碼,只需要將根節點作爲參數放入函數然後分別對左右子樹遞歸處理即可。(如同代碼1所示)
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode *root) {
if(!root)return true;
int root_left=0,root_right=0;
return CheckBal(root->left,root->right,&root_left,&root_right);
}
private:
bool CheckBal(TreeNode *Left,TreeNode *Right, int *depth_l,int *depth_r){
if(Left==nullptr&&Right==nullptr){
return true;
}
int depth_l_l=0,depth_l_r=0,depth_r_l=0,depth_r_r=0;
if(Left){
(*depth_l)++;
if(CheckBal(Left->left,Left->right,&depth_l_l,&depth_l_r)){
(*depth_l)+=max(depth_l_l,depth_l_r);
}else{
return false;
}
}
if(Right){
(*depth_r)++;
if(CheckBal(Right->left,Right->right,&depth_r_l,&depth_r_r)){
(*depth_r)+=max(depth_r_l,depth_r_r);
}else{
return false;
}
}
if(((*depth_l)+1<*depth_r)||((*depth_r)+1<*depth_l)){
return false;
}else{
return true;
}
}
};
解題思路2:由於是深度是非負的,因此可以通過-1來表示不平衡。從而避免了返回值不一致的問題(如第一種思路,爲了讓返回值爲bool型並記錄深度,不得不採取了傳引用的函數調用方式)。
代碼:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode *root) {
return TreeHeight(root)!=-1;
}
private:
int TreeHeight(TreeNode *root){
if(!root)return 0;
int H_left=TreeHeight(root->left);
int H_right=TreeHeight(root->right);
if((H_left==-1)||(H_right==-1)||(abs(H_left-H_right)>1)){
return -1;
}
return max(H_left,H_right)+1;
}
};