public class FullTree{
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int data) {
this.value = data;
}
}
public static boolean isF(Node head){
if(head == null){
return true;
}
Info data = process(head);
return data.nodes == (1 << data.height - 1);//节点数是否等于2^n - 1
}
public static class Info{//收集信息1.高度 2.节点数
public int height;
public int nodes;
public Info(int h,int n){
height = h;
nodes = n;
}
}
public static Info process(Node x){
if(x == null){
return new Info(0,0);
}
Info lefInfo = process(x.left);//收集左树的信息
Info righInfo = process(x.right);//收集右树的信息
//自己也要返回2个信息
int height = Math.max(lefInfo.height,righInfo.height) + 1;
int nodes = lefInfo.nodes + righInfo.nodes + 1;
return new Info(height,nodes);
}
}
满二叉树(递归)
于 2022-03-23 10:14:48 首次发布