给定一棵二叉树的头节点head,返回这颗二叉树是不是满二叉树
满二叉树(Full Tree):
国内定义 : 一个二叉树,如果每一个层的结点数都达到最大值,则这个二叉树就是满二叉树。也就是说,如果一个二叉树的层数为K,且结点总数是(2^k) -1 ,则它就是满二叉树。
public class 判断是否满二叉树 { public static class Node { public int value; public Node left; public Node right; public Node(int data) { this.value = data; } } public static boolean ans(Node head) { return process(head).isFull; } private static Info process(Node head) { if (head == null) { return new Info(0, 0, true); } Info leftInfo = process(head.left); Info rightInfo = process(head.right); int height = 0; int size = 0; boolean isFull = true; int leftHeight = 0; int leftSize = 0; int rightHeight = 0; int rightSize = 0; if (leftInfo != null) { leftHeight = leftInfo.height; leftSize = leftInfo.size; isFull = isFull && leftInfo.isFull; } if (rightInfo != null) { rightHeight = rightInfo.height; rightSize = rightInfo.size; isFull = isFull && rightInfo.isFull; } height = Math.max(leftHeight, rightHeight) + 1; size = leftSize + rightSize + 1; //1.如果左子树高度和右子树高度不同则不是满二叉树 //2.如果 2^高度-1 和 总节点数不相等则不是满二叉树 //"<<"比"-"优先级低 , (1 << height)加括号 if (leftHeight != rightHeight || ((1 << height) - 1) != size){ return new Info(height,size,false); } return new Info(height,size,isFull); } private static class Info { private int height; private int size; private boolean isFull; private Info(int h, int s, boolean is) { height = h; size = s; isFull = is; } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)