描述
Given a binary tree, determine if it is height-balanced.
判断一个二叉树是否为平衡二叉树
例子
思路
递归
对于每一个结点
为空时:是平衡结点
不为空时:当左右子树皆为平衡二叉树,且高度差小于2时,该结点为平衡二叉树
答案
- python
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
if not root:
return True
if self.isBalanced(root.left) and self.isBalanced(root.right) and abs(self.depth(root.left)-self.depth(root.right))<2:
return True
else:
return False
#树的深度
def depth(self, root:TreeNode) -> int:
if not root:
return 0
return 1 + max(self.depth(root.left), self.depth(root.right))
- java
* 好的方法
class Solution {
private boolean isBalanced=true;
public boolean isBalanced(TreeNode root) {
depth(root);
return isBalanced;
}
public int depth(TreeNode root) {
if (root==null) return 0;
int L = depth(root.left);
int R = depth(root.right);
if(Math.abs(L-R)>1) isBalanced=false;
return Math.max(L,R)+1;
}
}
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null)
return true;
if (isBalanced(root.left) && isBalanced(root.right) && Math.abs(depth(root.left)-depth(root.right))<2)
return true;
else
return false;
}
//树的深度
public int depth(TreeNode root)
{
if (root == null)
return 0;
return 1 + Math.max(depth(root.left), depth(root.right));
}
}