- Balanced Binary Tree
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 left and right subtrees of every node differ in height by no more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/
9 20
/
15 7
Return true.
java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
return balanced(root,0)>=0;
}
private int balanced(TreeNode root,int length){
if(root == null)
return length;
int l = balanced(root.left,length+1);
int r = balanced(root.right,length+1);
if(Math.abs(l-r)>1)
return -1;
return Math.max(l,r);
}
}
python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
return self.balanced(root,0)>=0
def balanced(self,root,length):
if root == None:
return length
l = self.balanced(root.left,length+1)
r = self.balanced(root.right,length+1)
if abs(l-r)>1:
return -1
return max(l,r)