package sy4;
import java.awt.*;
public class Test {
public static void main(String[] args) {
TreeNode root=new TreeNode(3);
TreeNode node1=new TreeNode(9);
TreeNode node2=new TreeNode(20);
TreeNode node3=new TreeNode(15);
TreeNode node4=new TreeNode(4);
root.left=node1;
root.right=node2;
node2.left=node3;
node2.right=node4;
Create c=new Create();
boolean balanced = c.isBalanced(root);
System.out.println(balanced);
}
}
class Create{
public void order(TreeNode node){
if (node==null){
return;
}
order(node.left);
System.out.print(node.val+" ");
order(node.right);
}
/**
* 判断是否为平衡二叉树
* @param root
* @return
*/
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
} else {
boolean x= Math.abs(height(root.left) - height(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
return x;
}
}
/**
* 求高度
* @param node
* @return
*/
public int height(TreeNode node){
if (node==null){
return 0;
}
int max= Math.max(height(node.left),height(node.right))+1;
return max;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
110. 平衡二叉树
最新推荐文章于 2024-08-21 13:55:04 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)