/**
* 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;
}
}