/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution {public: /** * @param root: The root of binary tree. * @return: True if this Binary tree is Balanced, or false. */ bool isBalanced(TreeNode * root) { // write your code here return treeDepth(root)!=-1; } int treeDepth(TreeNode * root) //计算以实参为根节点的树的深度,非平衡时直接返回-1;{ if (root==NULL) { return 0; } int leftDepth=treeDepth(root->left); int rightDepth=treeDepth(root->right); if (leftDepth==-1||rightDepth==-1||abs(leftDepth-rightDepth)>1) { return -1; } return max(leftDepth,rightDepth)+1;}};