这虽然是一道简单题,但是要找到最佳的解法还是比较困难的
最直接的思路
这道题,最直接的思路就是从上到下,判断每一个结点的左子树和右子树的高度差是否小于或等于1,所有结点都满足平衡二叉树的条件才能返回true。也可以根据后序遍历,从下往上判断。
但是,这个解法有个问题,就是我们在求位于上方的结点的最大高度的时候,其实已经把下方的结点的最大高度也给求出来了,但是我们并没有去存储这个信息,所以导致我们做了一些重复的步骤,因此,我们可以考虑存储这些信息。
使用Map结构存储高度信息
自顶向下,先求出每个结点的高度信息,再判断是否是平衡二叉树
import java.util.*;
public class Solution {
Map<TreeNode, Integer> heightMap;
public boolean IsBalanced_Solution(TreeNode root) {
heightMap = new HashMap<>();
heightMap.put(null, 0);
getHeight(root);
return judgeBalanced(root);
}
private boolean judgeBalanced(TreeNode root){
if(root == null)
return true;
int leftH = heightMap.get(root.left);
int rightH = heightMap.get(root.right);
return Math.abs(leftH - rightH) < 2 && judgeBalanced(root.left)
&& judgeBalanced(root.right);
}
private void getHeight(TreeNode root){
if(root == null)
return;
if(heightMap.containsKey(root)) return;
getHeight(root.left);
getHeight(root.right);
int leftH = heightMap.get(root.left);
int rightH = heightMap.get(root.right);
heightMap.put(root, 1 + Math.max(leftH, rightH));
}
}
后序遍历自底向上同时返回高度信息
上一个解法需要两次遍历,其实在获取高度信息的时候,我们就可以顺便判断以该结点为根节点的二叉树是不是平衡二叉树,并返回了。当然这就需要我们自底向上的判断了。
我的解法 (自定义高度类存储高度信息)
public class Solution {
class Height{
public int height;
public Height(){
height = 0;
}
}
public boolean IsBalanced_Solution(TreeNode root) {
return judgeBalanced(root, new Height());
}
private boolean judgeBalanced(TreeNode root, Height d) {
if(root == null)
return true;
Height leftD = new Height();
boolean left = judgeBalanced(root.left, leftD);
if (!left) return false;
Height rightD = new Height();
boolean right = judgeBalanced(root.right, rightD);
if (!right) return false;
d.height += 1 + Math.max(leftD.height, rightD.height);
return Math.abs(leftD.height - rightD.height) < 2;
}
}
他人的解法(不需要自定义类)
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
return getHeight(root) != -1;
}
private int getHeight(TreeNode root) {
if (root == null) return 0;
int left = getHeight(root.left);
if (left == -1) return -1;
int right = getHeight(root.right);
if (right == -1) return -1;
return Math.abs(left - right) > 1 ? -1 : 1 + Math.max(left, right);
}
}