解题思路

递归解决这题,我们需要计算每个节点下的左右子树的高度,若不符合平衡二叉树则直接返回false。

总共会出现3种情况

  1. 当前节点为空,返回0
  2. 当前节点的左右子树不为平衡树,返回-1
  3. 左右子树高度的绝对值差>1返回-1
  4. 返回1 + max(左树,右树)

代码

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 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 root is None:
return True
def getDepth(root):
if root is None:
return 0
leftDepth = getDepth(root.left)
if leftDepth == -1: return -1
rightDepth = getDepth(root.right)
if rightDepth == -1: return -1
return -1 if abs(leftDepth - rightDepth) > 1 else 1 + max(leftDepth, rightDepth)
return not (getDepth(root) == -1)

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
return !(getDepth(root) == -1);
}
int getDepth(TreeNode* root) {
if (root == NULL) return 0;
int leftDepth = getDepth(root->left);
int rightDepth = getDepth(root->right);
if (leftDepth == -1 || rightDepth == -1) return -1;
return abs(leftDepth - rightDepth) > 1 ? -1 : 1 + max(leftDepth, rightDepth);
}
};

Go

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isBalanced(root *TreeNode) bool {
if root == nil{
return true
}
return !(getDepth(root) == -1)
}

func getDepth(root *TreeNode) int{
if root == nil{
return 0
}
leftDepth := getDepth(root.Left)
rightDepth := getDepth(root.Right)
if leftDepth == -1 || rightDepth == -1{
return -1
}
// 左右子树高度差>1,不是平衡二叉树
if abs(leftDepth - rightDepth) > 1{
return -1
} else {
return 1 + max(leftDepth, rightDepth)
}
}

// 绝对值
func abs(a int) int{
if a < 0{
return -a
}
return a
}

// 取最大值
func max(a int, b int) int{
if (a >= b){
return a
}
return b
}