剑指 Offer 55 - II. 平衡二叉树
输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
class Solution:def depth(self, node):if not node:return 0return max(self.depth(node.left),self.depth(node.right))+1def isBalanced(self, root: TreeNode) -> bool:if not root:return Truereturn abs(self.depth(root.left)-self.depth(root.right))<=1 and self.isBalanced(root.left) and self.isBalanced(root.right)
后序遍历 + 剪枝 (从底至顶)
class Solution:def isBalanced(self, root: TreeNode) -> bool:def recur(root):if not root: return 0left = recur(root.left)if left == -1: return -1right = recur(root.right)if right == -1: return -1return max(left, right) + 1 if abs(left - right) <= 1 else -1return recur(root) != -1作者:jyd链接:https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/solution/mian-shi-ti-55-ii-ping-heng-er-cha-shu-cong-di-zhi/来源:力扣(LeetCode)著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
