将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。
输入格式:
输入第一行给出一个不超过20的正整数N
;第二行给出N
个互不相同的正整数,其间以空格分隔。
输出格式:
将输入的N
个正整数顺序插入一个初始为空的二叉搜索树。在第一行中输出结果树的层序遍历结果,数字间以1个空格分隔,行的首尾不得有多余空格。第二行输出YES
,如果该树是完全二叉树;否则输出NO
。
输入样例1:
9
38 45 42 24 58 30 67 12 51
输出样例1:
38 45 24 58 42 30 12 67 51
YES
输入样例2:
8
38 24 12 45 58 67 42 51
输出样例2:
38 45 24 58 42 12 67 51
NO
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
import java.util.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
left = null;
right = null;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int[] nums = new int[N];
for (int i = 0; i < N; i++) {
nums[i] = scanner.nextInt();
}
TreeNode root = buildBST(nums);
List<Integer> traversal = levelOrderTraversal(root);
boolean isComplete = isCompleteBinaryTree(root);
int ccc=0;
for (int num : traversal) {
if(ccc!=0){
System.out.print(" ");
}
System.out.print(num);
ccc=1;
}
System.out.println();
System.out.println(isComplete ? "YES" : "NO");
}
public static TreeNode buildBST(int[] nums) {
TreeNode root = null;
for (int num : nums) {
root = insert(root, num);
}
return root;
}
public static TreeNode insert(TreeNode root, int val) {
if (root == null) {
return new TreeNode(val);
}
if (val < root.val) {
root.right = insert(root.right, val);
} else {
root.left = insert(root.left, val);
}
return root;
}
public static List<Integer> levelOrderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
result.add(node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
return result;
}
public static boolean isCompleteBinaryTree(TreeNode root) {
if (root == null) {
return true;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
boolean hasNullChild = false;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
// 如果一棵树没有左子树,则后面的树都没有左子树
if (node.left == null) {
hasNullChild = true;
} else if (hasNullChild) {
return false;
} else {
queue.offer(node.left);
}
if (node.right == null) {
hasNullChild = true;
} else if (hasNullChild) {
return false;
} else {
queue.offer(node.right);
}
}
return true;
}
}