解法一:由上至下
/**
* 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 depth(TreeNode* root){
if(root == NULL){
return 0;
}
int left = depth(root->left);
int right = depth(root->right);
return max(left, right) + 1;
}
bool isBalanced(TreeNode* root) {
if(root == NULL){
return true;
}
int left = depth(root->left);
int right = depth(root->right);
return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
};
解法二:dfs
/**
* 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 dfsHeight(TreeNode* root){
if(root == NULL) return 0;
int left = dfsHeight(root->left);
if(left == -1) return -1;
int right = dfsHeight(root->right);
if(right == -1) return -1;
if(abs(right - left) > 1) return -1;
else return max(left, right) + 1;
}
bool isBalanced(TreeNode* root) {
if(root == NULL) return true;
if(dfsHeight(root) != -1) return true;
else return false;
}
};
网友评论