110 Balanced Binary Tree
110. Balanced Binary Tree
1. Question
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 depth of the two subtrees ofeverynode never differ by more than 1.
2. Implementation
(1) DFS
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
return dfs(root) != -1;
}
public int dfs(TreeNode node) {
if (node == null) {
return 0;
}
int leftHeight = dfs(node.left);
int rightHeight = dfs(node.right);
if (leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1) {
return -1;
}
return Math.max(leftHeight, rightHeight) + 1;
}
}
3. Time & Space Complexity
DFS: 时间复杂度: O(n), 空间复杂度: O(h)
Last updated
Was this helpful?