Skip to main content

balanced-binary-tree

110. Balanced Binary Tree

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

Example 1:

image

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

Example 2:

image

Input: root = [1,2,2,3,3,null,null,4,4] Output: false

Example 3:

Input: root = [] Output: true

Constraints:

  • The number of nodes in the tree is in the range [0, 5000].
  • -104 <= Node.val <= 104

根據題意,左側樹高和右側樹高的差如果大於 1 即沒有平衡,使用遞迴解。

/**
* 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)