/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */classSolution{publicbooleanisBalanced(TreeNoderoot){returndfs(root)!=-1;}privateintdfs(TreeNoderoot){if(root==null){return0;}intl=dfs(root.left);intr=dfs(root.right);if(l==-1||r==-1||Math.abs(l-r)>1){return-1;}return1+Math.max(l,r);}}
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcisBalanced(root*TreeNode)bool{vardfsfunc(*TreeNode)intdfs=func(root*TreeNode)int{ifroot==nil{return0}l,r:=dfs(root.Left),dfs(root.Right)ifl==-1||r==-1||abs(l-r)>1{return-1}return1+max(l,r)}returndfs(root)!=-1}funcabs(xint)int{ifx<0{return-x}returnx}
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */publicclassSolution{publicboolIsBalanced(TreeNoderoot){returndfs(root)!=-1;}privateintdfs(TreeNoderoot){if(root==null){return0;}intl=dfs(root.left);intr=dfs(root.right);if(l==-1||r==-1||Math.Abs(l-r)>1){return-1;}return1+Math.Max(l,r);}}
/* public class TreeNode {* public var val: Int* public var left: TreeNode?* public var right: TreeNode?* public init(_ val: Int) {* self.val = val* self.left = nil* self.right = nil* }* }*/classSolution{funcisBalanced(_root:TreeNode?)->Bool{returndfs(root)!=-1}privatefuncdfs(_root:TreeNode?)->Int{guardletroot=rootelse{return0}letleftDepth=dfs(root.left)letrightDepth=dfs(root.right)ifleftDepth==-1||rightDepth==-1||abs(leftDepth-rightDepth)>1{return-1}return1+max(leftDepth,rightDepth)}}