题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
// 使用递归来完成
// 比较左右子树的高度来判断是否为平衡二叉树
// 所以定义一个计算二叉树高度的方法
if(root == null ){
return true;
}
// 计算左右子树的高度
int leftDepth = getDepth(root.left);
int rightDepth = getDepth(root.right);
return Math.abs(leftDepth - rightDepth) <= 1 && IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
private int getDepth(TreeNode root){
if(root == null){
return 0;
}
// 计算高度,这里也需要递归操作
return Math.max(getDepth(root.left) , getDepth(root.right)) + 1;
}
}
思路:这里面涉及到两个知识。求二叉树的高度,利用递归。每一层,找左右子树的最大高度,然后加一。
判断是否是平衡二叉树,首先root的高度差是<= 1的,并且它的左右子树也得这样,所有最后return的部分是三个内容进行&&操作。
顺丰集团工作强度 274人发布