2025/9/15 【二叉树12】平衡二叉树
二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数。
二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数。
但leetcode中强调的深度和高度很明显是按照节点来计算的。
求深度适合用前序遍历,而求高度适合用后序遍历。
方法一:递归
关于根节点的深度究竟是1 还是 0,不同的地方有不一样的标准,leetcode的题目中都是以节点为一度,即根节点深度是1。但维基百科上定义用边为一度,即根节点的深度是0。
# 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: if self.get_height(root) != -1: return True else: return False def get_height(self, root): if not root: return 0 if (left_height := self.get_height(root.left)) == -1: return -1 if (right_height := self.get_height(root.right)) == -1: return -1 if abs(left_height - right_height) > 1: return -1 else: return 1 + max(left_height, right_height)
方法二:迭代
在104.二叉树的最大深度 中我们可以使用层序遍历来求深度,但是就不能直接用层序遍历来求高度了,这就体现出求高度和求深度的不同。
# 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: if not root: return True st = [] st.append(root) while st: node = st.pop() if abs(self.getDepth(node.left) - self.getDepth(node.right)) > 1: return False if node.right: st.append(node.right) if node.left: st.append(node.left) return True def getDepth(self, cur): if not cur: return 0 st = [] st.append(cur) depth = 0 result = 0 while st: node = st[-1] if node is not None: st.pop() st.append(node) st.append(None) depth += 1 if node.right: st.append(node.right) if node.left: st.append(node.left) else: st.pop() st.pop() depth -= 1 result = max(result, depth) return result