判断一棵二叉树是否是平衡二叉树
程序员文章站
2022-03-03 09:57:23
...
思路
递归判断每个节点及其子节点组成的树是否是平衡树
代码
package BinaryTree;
public class IsBalancedTree {
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int data) {
this.value = data;
}
}
public static class ReturnData{
public boolean isB;
public int level;
public ReturnData(boolean isB,int data){
this.isB=isB;
this.level=data;
}
}
public static boolean isBalance(Node head){
return process(head).isB;
}
public static ReturnData process(Node head){
if (head==null){
return new ReturnData(true,0);
}
ReturnData LeftReturnData=process(head.left);
if (LeftReturnData.isB==false){
return new ReturnData(false,0);
}
ReturnData RightReturnData=process(head.right);
if(RightReturnData.isB==false){
return new ReturnData(false,0);
}
if (Math.abs(LeftReturnData.level-RightReturnData.level)>1){
return new ReturnData(false,0);
}
return new ReturnData(true,Math.max(LeftReturnData.level,RightReturnData.level)+1);
}
public static void main(String[] args) {
Node head = new Node(1);
head.left = new Node(2);
head.right = new Node(3);
head.left.left = new Node(4);
head.left.right = new Node(5);
head.right.left = new Node(6);
head.right.right = new Node(7);
System.out.println(isBalance(head));
}
}
上一篇: 【Vue学习笔记】常用内部指令总结
下一篇: vue-指令总结