题目
输入一棵二叉树的根结点,判断该树是不是平衡二叉树。如果某二叉树中任意结点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
解题思路
在二叉树深度的基础上修改:计算树的深度,树的深度=max(左子树深度,右子树深度)+1。在遍历过程中,判断左右子树深度相差是否超过1,如果不平衡,则令树的深度=-1,用来表示树不平衡。
最终根据树的深度是否等于-1来确定是否为平衡树。
测试用例
1.功能测试(左斜树、右斜树、平衡或者不平衡树)
2.特殊测试(一个结点,null)
代码
package mySword;
public class balancedTree {
public static class TreeNode{
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val){
this.val = val;
}
}
public static boolean isBalancedTree(TreeNode root){
return getTreeDepth(root) != -1;
}
public static int getTreeDepth(TreeNode root){
if(root == null){
return 0;
}
int left = getTreeDepth(root.left);
if(left == -1){
return -1;
}
int right = getTreeDepth(root.right);
if(right == -1){
return -1;
}
return Math.abs(left - right) > 1 ? -1 : 1 + Math.max(left, right);
}
public static void main(String[] args) {
TreeNode root = new TreeNode(0);
TreeNode node1 = new TreeNode(1);
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(3);
TreeNode node4 = new TreeNode(4);
TreeNode node5 = new TreeNode(5);
TreeNode node6 = new TreeNode(6);
TreeNode node7 = new TreeNode(7);
TreeNode node8 = new TreeNode(8);
root.left = node1;
root.right = node2;
root.left.left = node3;
root.left.right = node4;
root.right.left = node5;
root.right.right = node6;
root.right.right.right = node7;
root.right.right.right.right = node8;
Boolean flag = isBalancedTree(root);
System.out.println(flag);
}
}
总结