檢測一個樹是否平衡,不需要求出高度,而是從底到頂檢測是否平衡,這樣才算法時間復雜度為O(n)。但是需要額外的O(logn)的空間
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isBalanced(TreeNode *root) { return checkBalance(root) >= 0; } int checkBalance(TreeNode *root){ if(root == NULL) return 0; int left = checkBalance(root->left); int right = checkBalance(root->right); if(left < 0 || right < 0 || abs(left-right) > 1) return -1; return max(left,right) +1; } };