递归法,后序遍历:
递归的返回值是以传入结点为根结点的二叉树的高度。
class Solution {
public:
int getDepth(TreeNode* node) {
if (node == NULL) return 0;
int leftDepth = getDepth(node->left);
if (leftDepth == -1) return -1;
int rightDepth = getDepth(node->right);
if (rightDepth == -1) return -1;
int result;
if (abs(leftDepth - rightDepth) > 1) return -1;
else {
result = 1 + max(leftDepth, rightDepth);
}
return result;
}
bool isBalanced(TreeNode* root) {
return getDepth(root) == -1 ? false : true;
}
};