LeetCode 110. 平衡二叉树

题目描述

110. 平衡二叉树

image-20230305213112788

image-20230305213108413

思路分析

要判断一个二叉树是否是平衡的,我们可以使用递归的方法。

image-20250510104929833

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
func isBalanced(root *TreeNode) bool {
	// 返回高度或 -1 表示不平衡
	var height func(node *TreeNode) int
	height = func(node *TreeNode) int {
		if node == nil {
			return 0 // 空树高度为 0
		}

		leftHeight := height(node.Left)   // 递归计算左子树高度
		rightHeight := height(node.Right) // 递归计算右子树高度

		// 如果左子树或右子树不平衡,返回 -1
		if leftHeight == -1 || rightHeight == -1 || abs(leftHeight-rightHeight) > 1 {
			return -1
		}

		return max(leftHeight, rightHeight) + 1 // 返回当前节点的高度
	}

	return height(root) != -1 // 如果返回值不为 -1,说明树是平衡的
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func isBalanced(root *TreeNode) bool {
	if root == nil {
		return true
	}
	left, right := depth(root.Left), depth(root.Right)
	if abs(left, right) > 1 {
		return false
	}
	return isBalanced(root.Left) && isBalanced(root.Right)
}

func depth(root *TreeNode) int {
	if root == nil {
		return 0
	}
	return max(depth(root.Left), depth(root.Right)) + 1
}

func abs(a, b int) int {
	if a > b {
		return a - b
	}
	return b - a
}

➡️ 点击查看 Java 题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        if (Math.abs(depth(root.left) - depth(root.right)) > 1) {
            return false;
        }
        return isBalanced(root.left) && isBalanced(root.right);
    }

    public int depth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return Math.max(depth(root.left), depth(root.right)) + 1;
    }
}
本文作者:
本文链接: https://hgnulb.github.io/blog/2025/64786890
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!