原题
https://leetcode.cn/problems/balanced-binary-tree/description/
思路
2个递归, 求每个节点的深度和判断每个节点是否为平衡二叉树
复杂度
时间:O(n)
空间:O(n)
Python代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def depth(root):
if not root:
return 0
return 1 + max(depth(root.left), depth(root.right))
if not root:
return True
return (
abs(depth(root.left) - depth(root.right)) <= 1
and self.isBalanced(root.left)
and self.isBalanced(root.right)
)
Go代码
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func depth(root *TreeNode) int {
if root == nil {
return 0
}
return 1 + max(depth(root.Left), depth(root.Right))
}
func isBalanced(root *TreeNode) bool {
if root == nil {
return true
}
return math.Abs(float64(depth(root.Left)-depth(root.Right))) <= 1 &&
isBalanced(root.Left) && isBalanced(root.Right)
}
平衡二叉树判定与实现
1122

被折叠的 条评论
为什么被折叠?



