Solution1:
转载自:https://www.nowcoder.com/profile/7699453/codeBookDetail?submissionId=15222689
这种用两个递归的方法还是第一次见,重点学习下depth的写法!
20181010整理代码
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Balance {
public:
bool isBalance(TreeNode* root) {
// write code here
if(root == NULL)
return true;
int diff = depth(root->left) - depth(root->right);
if(abs(diff) > 1)
return false;
else
return isBalance(root->left)
&& isBalance(root->right);
}
int depth(TreeNode *root) {
if(!root)
return 0;
int left = depth(root->left);
int right = depth(root->right);
return max(left, right) + 1;
}
};
原答案
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Balance {
public:
bool isBalance(TreeNode* root) {
// write code here
if(root == NULL)
return true;
int diff = depth(root->left) - depth(root->right);
if(abs(diff) > 1)
return false;
else
return true;
return isBalance(root->left) && isBalance(root->right);
}
int depth(TreeNode *root) {
if(root == NULL)
return 0;
int left = depth(root->left);
int right = depth(root->right);
return (left > right)? (left + 1):(right + 1);
}
};
Solution2:
《剑指offer》上的思路更好,时间复杂度更低。参考链接:
https://blog.csdn.net/Allenlzcoder/article/details/79685413