题解 | #判断是不是平衡二叉树 01 02#
判断是不是平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
public class Solution {
/*
//计算该子树深度函数
public int deep(TreeNode root) {
//空节点深度为0
if (root == null)
return 0;
//递归算左右子树的深度
int left = deep(root.left);
int right = deep(root.right);
//子树最大深度加上自己
return (left > right) ? left + 1 : right + 1;
}
public boolean IsBalanced_Solution(TreeNode root) {
//空树为平衡二叉树
if (root == null)
return true;
int left = deep(root.left);
int right = deep(root.right);
//左子树深度减去右子树相差绝对值大于1
if (left - right > 1 || left - right < -1)
return false;
//同时,左右子树还必须是平衡的
return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
*/
public boolean IsBalanced_Solution(TreeNode root) {
//空树也是平衡二叉树
if(root == null)
return true;
return getdepth(root) != -1;
}
public int getdepth(TreeNode root) {
if(root == null)
return 0;
//递归计算当前root左右子树的深度差
int left = getdepth(root.left);
//当前节点左子树不平衡,则该树不平衡
if(left < 0)
return -1;
int right = getdepth(root.right);
//当前节点右子树不平衡,则该树不平衡
if(right < 0)
return -1;
//计算深度差
return Math.abs(left - right) > 1 ? -1 : 1 + Math.max(left, right);
}
}
看不懂题解。。。。
回头看看视频
