原题链接:https://leetcode.com/problems/balanced-binary-tree/
1. 题目介绍
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
给定一个二叉树,判断它是否为平衡二叉树。平衡二叉树就是指每个节点的左右子树长度相差不超过1的二叉树。
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
Return false.
2. 解题思路
方法1 计算左右子树高度
可以计算出每个节点的左右子树高度差,如果高度差大于1,则返回false。如果没有节点,则相当于两个子树的高度都是0,则返回true。其他的情况,使用递归计算左右子树是否为平衡的,将左子树和右子树的情况进行与运算返回。
实现代码
class Solution {
public boolean isBalanced(TreeNode root) {
return cur(root);
}
public boolean cur(TreeNode root){
if(root == null){
return true;
}
int diff = Math.abs( depth(0,root.left) - depth(0,root.right) );
if(diff>1){
return false;
}
return cur(root.left) && cur(root.right);
}
public int depth(int d, TreeNode root){
if(root == null){
return d;
}
if(root.left == null && root.right == null){
return d+1;
}
return Math.max(depth(d+1,root.left) , depth(d+1,root.right) ) ;
}
}
方法2 直接返回是否为平衡树
注:该方法来自 https://www.cnblogs.com/grandyang/p/4045660.html 有兴趣的读者可以直接去看原文。
是如果我们发现子树不平衡,则不计算具体的深度,而是直接返回-1。如果是平衡的,就返回具体的深度。
对于每一个节点,我们通过checkDepth方法递归获得左右子树的深度,如果子树是平衡的,则返回真实的深度,若不平衡,直接返回-1,此方法时间复杂度O(N),空间复杂度O(H),参见代码如下:
class Solution {
public boolean isBalanced(TreeNode root) {
return(findDepth(root) == -1 ? false : true);
}
public int findDepth(TreeNode root){
if(root == null){
return 0;
}
//判断左子树是否为平衡树,如果不是直接返回-1,不必做多余计算
int left = findDepth(root.left);
if(left == -1){
return -1;
}
//判断右子树是否为平衡树,如果不是直接返回-1,不必做多余计算
int right = findDepth(root.right);
if(right == -1){
return -1;
}
//此时左右子树都是平衡树了
//现在开始判断以root为根节点的树是不是平衡树
//如果不是直接返回-1
int diff = Math.abs(left - right);
if(diff > 1){
return -1;
}
//到这一步,已经确认了左子树、右子树、root树本身都是平衡树
//可以返回root树的真实长度了
return 1 + Math.max(left,right);
}
}