110. Balanced Binary Tree

110. Balanced Binary Tree

检查树是否平衡,即左右子树的高度差小于等于1

// time: O(N)

bool isBalanced(TreeNode* root) {
    if (root==NULL) return true;
    int left=depth(root->left);
    int right=depth(root->right);
	// 每一个子树都要严格符合要求
    return abs(left-right)<=1 && isBalanced(root->left) && isBalanced(root->right);
}

int depth(TreeNode* root) {
    if (root==NULL) return 0;
    return max(depth(root->left), depth(root->right)) + 1;
}

只遍历一次,后序遍历 bottom up

bool isBalanced(TreeNode* root) {
    int a;
    return ban(root, a);
}

bool ban(TreeNode* root, int& d) {
    if (root == NULL) {
        d = 0;
        return true;
    }
    int left, right;
    if (ban(root->left, left) && ban(root->right, right)) {
        int diff = left-right;
        if (diff >= -1 && diff <= 1) {
            d = 1 + (left > right ? left : right);
            return true;
        }
    }
    return false;
}

#tree