/**
* 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 {
private:
int indicator = 1;
public:
int maxDepth(TreeNode* root) {
if(root == NULL)
return 0;
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
if(leftDepth > rightDepth )
return leftDepth + 1;
else
return rightDepth + 1;
}
void check(TreeNode *root) {
if(root == NULL)
return;
if(indicator == 0)
return;
int heightDiffer = maxDepth(root->left) - maxDepth(root->right);
if(heightDiffer >1 || heightDiffer < -1) {
indicator = 0;
return;
}
check(root->left);
check(root->right);
}
bool isBalanced(TreeNode* root) {
check(root);
if(indicator == 0)
return false;
else
return true;
}
};
经过一段时间的训练。发现上面的做法会多次遍历同一节点。受到剑指offer P209面试题39题目二解法的启示重写例如以下。执行时间只为曾经的一半8ms(这一次换成了c语言。由于大多数嵌入式公司要求的是c)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isBalancedInner(struct TreeNode* root, int* height);
bool isBalanced(struct TreeNode* root)
{
int height;
return isBalancedInner(root, &height);
}
bool isBalancedInner(struct TreeNode* root, int* height)
{
if(!root)
{
*height = 0;
return true;
}
int leftHeight, rightHeight;
bool leftIsBalanced = isBalancedInner(root->left, &leftHeight);
bool rightIsBalanced = isBalancedInner(root->right, &rightHeight);
if(!leftIsBalanced || !rightIsBalanced)
return false;
else
{
*height = leftHeight > rightHeight ? (leftHeight + 1) : (rightHeight + 1);
return (leftHeight - rightHeight > 1) || (leftHeight - rightHeight < -1) ? false : true;
}
}