1. 题目描述
判断二叉树是不是满二叉树
2. 测试案例
- 树空
- 树不空
3. 解题
3.1 思路一:左子树怎样,右子树怎样,左右子树满足某条件
假设当前结点为x,则:
- 只有当左子树为满二叉树,且右子树为满二叉树,且左右子树高度相同时,x才会满二叉树。
- 其余情况下x均为非满二叉树。
代码:
public class Main {
static class Node {
public int value;
public Node left;
public Node right;
public Node(int value) {
this.value = value;
}
}
static class Info {
public boolean isFBT; // 是否是满二叉树
public int height; // 树高
public Info(boolean isFBT, int height) {
this.isFBT = isFBT;
this.height = height;
}
}
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
System.out.println(isFullBinaryTree(root));
}
// 判断一颗树是否为满二叉树
public static boolean isFullBinaryTree(Node root) {
return pos(root).isFBT;
}
// 使用递归后序遍历解题
public static Info pos(Node cur) {
/* 0. 边界条件 */
if (cur == null)
return new Info(true, 0);
/* 1. 获取左右子树信息 */
Info leftInfo = pos(cur.left);
Info rightInfo = pos(cur.right);
/* 2. 实例化当前结点的Info对象,将info对象的信息设置正确,并返回该对象 */
Info info = new Info(false, Math.max(leftInfo.height, rightInfo.height) + 1);
if (leftInfo.isFBT && rightInfo.isFBT && leftInfo.height == rightInfo.height)
info.isFBT = true;
return info;
}
}
3.2 思路二:只需要知道某些字段,然后根据公式可得到结果
假设当前结点为x,则:
只要知道x结点所在树的高h和总结点n,如果 2h - 1 == n ,则x结点所在树为满二叉树,反之,则为非满二叉树。
public class Main {
static class Node {
public int value;
public Node left;
public Node right;
public Node(int value) {
this.value = value;
}
}
static class Info {
public int nodeCount; // 所在树的结点数
public int height; // 所在树的树高
public Info(int nodeCount, int height) {
this.nodeCount = nodeCount;
this.height = height;
}
}
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
System.out.println(isFullBinaryTree(root));
}
// 判断一颗树是否为满二叉树
public static boolean isFullBinaryTree(Node root) {
Info info = pos(root);
return Math.pow(2, info.height) - 1 == info.nodeCount ? true : false;
}
// 使用递归后序遍历解题
public static Info pos(Node cur) {
/* 0. 边界条件 */
if (cur == null)
return new Info(0, 0);
/* 1. 获取左右子树信息 */
Info leftInfo = pos(cur.left);
Info rightInfo = pos(cur.right);
/* 2. 实例化当前结点的Info对象,将info对象的信息设置正确,并返回该对象 */
Info info = new Info(leftInfo.nodeCount + rightInfo.nodeCount + 1, Math.max(leftInfo.height, rightInfo.height) + 1);
return info;
}
}