Balanced Binary Tree
Thoughts
Code
class Solution {
private int depth(TreeNode node) {
if (node == null) {
return 0;
}
int left = depth(node.left);
int right = depth(node.right);
if (left == -1 || right == -1 || Math.abs(left - right) > 1) {
return -1;
}
return Math.max(left, right) + 1;
}
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
if (depth(root) == -1) {
return false;
} else {
return true;
}
}
}Analysis
Ver.2
Previous1430. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary TreeNextBinary Tree Tilt
Last updated