这道题和二叉树的深度求解思路差不多,我们求深度的时候顺便求出子树深度差,大于1则标志位设为false否则就是true
思路一:分治法或者说(dfs+剪枝)
代码如下:
public class Solution {
Boolean flag=true;
public boolean IsBalanced_Solution(TreeNode root) {
TreeDept(root);
return flag;
}
private int TreeDept(TreeNode root)
{
if(root==null)
return 0;
int leftDept=TreeDept(root.left);
int rightDept=TreeDept(root.right);
if(Math.abs(leftDept-rightDept)>1)
{
flag=false;
}
return leftDept>rightDept?leftDept+1:rightDept+1;
}
}
剪枝优化
public class Solution {
Boolean flag=true;
public boolean IsBalanced_Solution(TreeNode root) {
TreeDept(root);
return flag;
}
private int TreeDept(TreeNode root)
{
if(root==null)
return 0;
int leftDept=TreeDept(root.left);
if(leftDept==-1)
return -1;
int rightDept=TreeDept(root.right);
if(rightDept==-1)
return -1;
if(Math.abs(leftDept-rightDept)>1)
{
flag=false;
return -1;//提前返回,剪枝
}
return leftDept>rightDept?leftDept+1:rightDept+1;
}
}
时间最坏退化链表 O(N) 空间最好单边递归栈O(logN),最坏O(N)