0%

leetCode-110:Balanced Binary Tree

问题描述

给定一个二叉树,要求判断这颗树是否是平衡二叉树。题目链接:**点我**

样例输入输出

输入:[1]

输出:true

输入:[1, 2]

输出:

问题解法

平衡二叉树的定义,要求左右子树的高度差不能超过1,且左右子树都是平衡二叉树。根据平衡二叉树的定义进行递归求解,由于要算出子树的高度和判断子树是否是平衡树,为了不重复计算,在计算高度的同时判断子树是否是平衡二叉树,如果不是,则返回-1,如果是,则返回树的高度,方便上层节点的计算。代码如下

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
int height = calcHeight(root);
return height >= 0;
}

private int calcHeight(TreeNode root) {
if (root == null) {
return 0;
}

int left = calcHeight(root.left);
int right = calcHeight(root.right);
if (left == -1 || right == -1 || Math.abs(left - right) > 1) {
return -1;
}

return Math.max(left, right) + 1;
}
}