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.


    Example 1:
    Given the following tree [3,9,20,null,null,15,7]:
    3
    / \
    9 20
    / \
    15 7
    Return true.

    Example 2:
    Given the following tree [1,2,2,3,3,null,null,4,4]:
    1
    / \
    2 2
    / \
    3 3
    / \
    4 4
    Return false.

    Runtime: 16 ms, faster than 56.86% of C++ online submissions for Balanced Binary Tree.
    Memory Usage: 16.5 MB, less than 100.00% of C++ online submissions for Balanced Binary Tree.

    1. /**
    2. * Definition for a binary tree node.
    3. * struct TreeNode {
    4. * int val;
    5. * TreeNode *left;
    6. * TreeNode *right;
    7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    8. * };
    9. */
    10. class Solution {
    11. public:
    12. bool isBalanced(TreeNode* root) {
    13. int height = 0;
    14. return check(root, height);
    15. }
    16. bool check(TreeNode *root, int& height) {
    17. if (root == NULL) {
    18. height = 0;
    19. return true;
    20. }
    21. int leftHeight = 0;
    22. int rightHeight = 0;
    23. if (!check(root->left, leftHeight)) {
    24. return false;
    25. }
    26. if (!check(root->right, rightHeight)) {
    27. return false;
    28. }
    29. if (abs(leftHeight - rightHeight) > 1) {
    30. return false;
    31. }
    32. height = max(leftHeight, rightHeight) + 1;
    33. return true;
    34. }
    35. };

    Runtime: 88 ms, faster than 85.22% of JavaScript online submissions for Balanced Binary Tree.
    Memory Usage: 43.2 MB, less than 41.05% of JavaScript online submissions for Balanced Binary Tree.

    1. /**
    2. * Definition for a binary tree node.
    3. * function TreeNode(val, left, right) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.left = (left===undefined ? null : left)
    6. * this.right = (right===undefined ? null : right)
    7. * }
    8. */
    9. /**
    10. * @param {TreeNode} root
    11. * @return {boolean}
    12. */
    13. var isBalanced = function(root) {
    14. function getDepth(node) {
    15. if (!node) {
    16. return 0;
    17. }
    18. const left = getDepth(node.left);
    19. if (left === -1) {
    20. return -1;
    21. }
    22. const right = getDepth(node.right);
    23. if (right === -1) {
    24. return -1;
    25. }
    26. const dis = Math.abs(left - right);
    27. return dis <= 1 ? Math.max(left, right) + 1 : -1;
    28. }
    29. return getDepth(root) !== -1;
    30. };