[leetcode] 110. 平衡二叉树 Balanced Binary Tree
给定一个二叉树判断它是否是平衡二叉树示例 1输入root [3,9,20,null,null,15,7] 输出true示例 2输入root [1,2,2,3,3,null,null,4,4] 输出false示例 3输入root [] 输出true提示树中的节点数在范围 [0, 5000] 内-104 Node.val 104Python实现这道题虽然是leetcode的easy的题目但是写出来还是不容易平衡二叉树的每一层都需要判断左右子树的高度差如果知道这个就需要写一个求高度的函数还有一个递归遍历左右子树的函数写完这些就基本上差不多了。# Definition for a binary tree node.# class TreeNode:# def __init__(self, val0, leftNone, rightNone):# self.val val# self.left left# self.right rightclassSolution:defgetDepth(self,root):ifnotroot:return0returnmax(self.getDepth(root.left),self.getDepth(root.right))1defisBalanced(self,root:Optional[TreeNode])-bool:ifnotroot:returnTrueleftself.getDepth(root.left)rightself.getDepth(root.right)ifabs(left-right)1:returnFalsereturnself.isBalanced(root.left)andself.isBalanced(root.right)另一种写法如下思路大差不差classSolution:defgetHeight(self,root):ifrootisNone:return0left_heightself.getHeight(root.left)right_heightself.getHeight(root.right)ifleft_height-1orright_height-1:return-1ifabs(left_height-right_height)1:return-1returnmax(left_height,right_height)1defisBalanced(self,root:Optional[TreeNode])-bool:returnself.getHeight(root)!-1