/** * 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);}}
方法二
1 2 3 4 5 6 7 8 9101112131415161718192021
# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = NoneclassSolution:defisBalanced(self,root:TreeNode)->bool:defdfs(root):ifrootisNone:return(True,0)l,ld=dfs(root.left)r,rd=dfs(root.right)d=max(ld,rd)+1iflandrandabs(ld-rd)<=1:return(True,d)return(False,d)returndfs(root)[0]