递归标准思路,拆解子问题
public class Solution { static boolean res=true; public boolean IsBalanced_Solution(TreeNode root) { if(root==null){ return true; } fun(root); return res; } //返回当前树深度度 public int fun(TreeNode root){ if(root==null){ return 0; } int leftlength=fun(root.left); int rightlength=fun(root.right); //如果当前节点的左右子树深度差超过1,直接把结果标识更新为false if(Math.abs(leftlength-rightlength)>1){ res=false; } //左右子树深度合法,则返回大深度+1(加上当前头) return Math.max(leftlength,rightlength)+1; } }