Isaac Emmanuel
15 Jun 2024•EasyC++ / Python / TypeScript

Balanced Binary Tree

C++, Python and TypeScript solutions for Balanced Binary Tree.

The Balanced Binary Tree solutions are below.

Solution files

Python•balanced-binary-tree/synced-solution.py
class Solution:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        def getHeight(node):
            if not node:
                return 0
            left_height = getHeight(node.left)
            if left_height == -1:
                return -1
            right_height = getHeight(node.right)
            if right_height == -1:
                return -1
            if abs(left_height - right_height) > 1:
                return -1
            return max(left_height, right_height) + 1
        return getHeight(root) != -1
C++•balanced-binary-tree/synced-solution.cpp
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        return getHeight(root) != -1;
    }
private:
    int getHeight(TreeNode* node) {
        if (!node) return 0;
        int left_height = getHeight(node->left);
        if (left_height == -1) return -1;
        int right_height = getHeight(node->right);
        if (right_height == -1) return -1;
        if (abs(left_height - right_height) > 1) return -1;
        return max(left_height, right_height) + 1;
    }
};
TypeScript•balanced-binary-tree/synced-solution.ts
function isBalanced(root: TreeNode | null): boolean {
    function getHeight(node: TreeNode | null): number {
        if (!node) return 0;
        const left_height = getHeight(node.left);
        if (left_height === -1) return -1;
        const right_height = getHeight(node.right);
        if (right_height === -1) return -1;
        if (Math.abs(left_height - right_height) > 1) return -1;
        return Math.max(left_height, right_height) + 1;
    }
    return getHeight(root) !== -1;
}