DEV Community 👩‍💻👨‍💻

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

Input: root = [3,9,20,null,null,15,7]
Output: true

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isBalanced = function(root) {
    let flag = true;

    var height = function(r){
        if(!r) return 0;

        let num1 = height(r.left);
        let num2 = height(r.right);
        let res = num1 - num2;

        if(res < -1 || res > 1) flag = false;

    return Math.max(num1,num2) + 1;
    }

    height(root);
    return flag;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Life is too short to browse without dark mode