首页 > 其他 > 详细

判断二叉树是不是满二叉树

时间:2020-05-30 21:44:40      阅读:51      评论:0      收藏:0      [点我收藏+]
package algorithm.tree;

/**
* 判断二叉树是不是满二叉树
*/
public class IsFull {

public static boolean isFull(Node node) {
return process(node).isFull;
}

private static ResultInfo process(Node node) {
if (node == null) {
return new ResultInfo(true, 0);
}
ResultInfo leftInfo = process(node.left);
ResultInfo rightInfo = process(node.right);
boolean isFull = leftInfo.isFull && rightInfo.isFull && leftInfo.height == rightInfo.height;
int height = Math.max(leftInfo.height, rightInfo.height) + 1;
return new ResultInfo(isFull, height);
}

public static boolean isFull1(Node head) {
if (head == null) {
return true;
}
int height = h(head);
int nodes = n(head);
return (1 << height) - 1 == nodes;
}

public static int h(Node head) {
if (head == null) {
return 0;
}
return Math.max(h(head.left), h(head.right)) + 1;
}

public static int n(Node head) {
if (head == null) {
return 0;
}
return n(head.left) + n(head.right) + 1;
}

// for test
public static Node generateRandomBST(int maxLevel, int maxValue) {
return generate(1, maxLevel, maxValue);
}

// for test
public static Node generate(int level, int maxLevel, int maxValue) {
if (level > maxLevel || Math.random() < 0.5) {
return null;
}
Node head = new Node((int) (Math.random() * maxValue));
head.left = generate(level + 1, maxLevel, maxValue);
head.right = generate(level + 1, maxLevel, maxValue);
return head;
}

public static void main(String[] args) {
int maxLevel = 5;
int maxValue = 100;
int testTimes = 1000000;
for (int i = 0; i < testTimes; i++) {
Node head = generateRandomBST(maxLevel, maxValue);
boolean isFull1 = isFull1(head);
boolean isFull = isFull(head);
if (isFull1 != isFull) {
System.out.println("Oops!");
}
}
System.out.println("finish!");
}

/**
* 向左右子树索要信息
*/
public static class ResultInfo {

// 是否是满二叉树
public boolean isFull;

// 树高度
public int height;

public ResultInfo(boolean isFull, int height) {
this.isFull = isFull;
this.height = height;
}

}

/**
* 二叉树结构
*/
public static class Node {

public int value;

public Node left;

public Node right;

public Node(int value) {
this.value = value;
}

}

}

/* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */

判断二叉树是不是满二叉树

原文:https://www.cnblogs.com/laydown/p/12994481.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!