思路
用后序分别求出每一个节点的左子树和右子树高度,然后判断是否符合定义,再判断两个子树是否符合定义
代码
class Solution {
public:int getDepth(TreeNode* node){if(node == nullptr) return 0;return max( getDepth(node->left), getDepth(node->right)) + 1;}bool isBalanced(TreeNode* root) {if(root == nullptr) return true;int leftDepth = getDepth(root->left);int rightDepth = getDepth(root->right);if(abs(rightDepth - leftDepth) > 1) return false;return isBalanced(root->left) && isBalanced(root->right);}
};