完全二叉树判定
pta题号 L3-010 判断一棵树是否是完全二叉树的思路:
- 如果树为空,则直接返回错
- 如果树不为空:层序遍历二叉树
- 如果一个结点左右孩子都不为空,则pop该节点,将其左右孩子入队列;
- 如果遇到一个结点,左孩子为空,右孩子不为空,则该树一定不是完全二叉树;
- 如果遇到一个结点,左孩子不为空,右孩子为空;或者左右孩子都为空;则该节点之后的队列中的结点都为叶子节点;该树才是完全二叉树,否则就不是完全二叉树;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
Tree tree = new Tree();
for (int i = 0; i < n; i++) {
int num = in.nextInt();
Node node = new Node(num);
tree.addNode(node);
}
System.out.println(tree.judge()?"\nYES":"\nNO");
}
static class Node {
int val;
Node root;
Node left;
Node right;
public Node(int val) {
this.val = val;
}
}
static class Tree {
Node root;
public void addNode(Node node) {
if (root == null) {
root = node;
} else {
build(node, root);
}
}
private void build(Node node, Node root) {
if (node.val > root.val) {
if (root.left == null) {
root.left = node;
node.root = root;
}
else
build(node, root.left);
} else {
if (root.right == null) {
root.right = node;
node.root = root;
} else {
build(node, root.right);
}
}
}
public boolean judge() {
Queue<Node> queue = new LinkedList<>();
//2.2算法的条件
boolean flag = false;
boolean res = true;
//控制空格的
boolean first = false;
if (root == null)
res = false;
queue.offer(root);
while (!queue.isEmpty()) {
Node cur = queue.poll();
if (first) System.out.print(" ");
first = true;
System.out.print(cur.val);
if (flag) {
if (cur.left!=null || cur.right!=null)
res = false;
}
if (cur.left != null && cur.right != null) {
queue.offer(cur.left);
queue.offer(cur.right);
} else if (cur.left == null && cur.right != null) {
res = false;
queue.offer(cur.right);
} else {
flag = true;
if (cur.left!=null) queue.offer(cur.left);
}
}
return res;
}
}
}
Loading...