110. Balanced Binary Tree

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(!root) return true;

        // 走訪左邊的樹
        int left = getHeight(root->left);

        // 走訪右邊的樹
        int right = getHeight(root->right);

        return abs(right - left) < 2 && isBalanced(root->left) && isBalanced(root->right);
    }
    int getHeight(TreeNode* root) {
        if(!root) return -1;
        // 每遞迴一次,height + 1
        return 1 + max(getHeight(root->left), getHeight(root->right));
    }
};
  • T: O(N)O(N)
  • S: O(N)O(N)