2020软件工程作业04
| 这个作业属于哪个课程 | https://edu.cnblogs.com/campus/zswxy/2018SE |
| ---- | ---- | ---- |
| 这个作业要求在哪里 | https://edu.cnblogs.com/campus/zswxy/2018SE/homework/11406 |
| 这个作业的目标 |冒泡排序、二叉树
题目名称:寻找数组中第K大是数 考察算法:排序算法
做题思路:
数组存放值,循环比较。
从第一个值开始,依次向后比较值的大小,小的就放前面,大的放后面到最后一个值,依次排序。
解题代码:
package firstjava;
import java.util.Scanner;
import java.util.Arrays;
public class order {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] array1=new int[n];
for (int i=0;i<array1.length;i++){
array1[i]=sc.nextInt();
}
int n2=sc.nextInt();
int[] array2=new int[n2];
for(int i=0;i<n2;i++){
int l=sc.nextInt();
int r=sc.nextInt();
int k=sc.nextInt();
int[] array3=new int[r-l+1];
for(int j=0;j<r-l+1;j++){
array3[j]=array1[j+l-1];
}
Arrays.sort(array3);
System.out.println(array3[r-l+1-k]);
}
}
}

题目名称:二叉树的先、中、后 序遍历与层级遍历 考察算法: dfs + bfs搜索算法
解题思路:
先(根)序遍历:根节点、左子树、右子树;
中(根)序遍历:左子树、根节点、右子树;
后(根)序遍历:左子树、右子树、根节点;
解题代码:
package firstjava;
import java.util.LinkedList;
public class erchashu{
public static void main(String[] args){
/*
作业要求:叉树的先、中、后 序遍历与层级遍历
自己实现四个方法,main方法中调用,将结果打印到控制台
*/
/* 二叉树的结构
A
/ \
T 6
/
D
/ \
N 5
/ \ /
B 4 1
\
9
*/
Node root = into();
// 先序遍历
System.out.println("先序遍历");
A(root);
System.out.println("\n");
// 中序遍历
System.out.println("中序遍历");
B(root);
System.out.println("\n");
// 后续遍历
System.out.println("后序遍历");
C(root);
System.out.println("\n");
// 层级遍历
System.out.println("层级遍历");
D(root);
System.out.println("\n");
}
private static void A(Node tree) {
// TODO 先序遍历
if(tree!=null) {
System.out.print(tree.data+" ");
A(tree.l);
A(tree.r);
}
}
private static void B(Node tree) {
// TODO 中序遍历
if(tree!=null) {
B(tree.l);
System.out.print(tree.data+" ");
B(tree.r);
}
}
private static void C(Node tree) {
// TODO 后续遍历
if(tree!=null) {
C(tree.l);
C(tree.r);
System.out.print(tree.data+" ");
}
}
private static void D(Node tree){
//TODO 层级遍历
if (tree != null) {
LinkedList<Node> queue = new LinkedList<Node>();
queue.add(tree);
Node node = null;
while (!queue.isEmpty()) {
node = (Node) queue.pop();
System.out.print(node.data + " ");
if (node.l != null) {
queue.add(node.l);
}
if (node.r != null) {
queue.add(node.r);
}
}}
}
// 构建一颗树,返回根节点
private static Node into(){
Node root = new Node("A");
Node node1 = new Node("T");
Node node2 = new Node("D");
Node node3 = new Node("N");
Node node4 = new Node("B");
Node node5 = new Node("6");
Node node6 = new Node("5");
Node node7 = new Node("4");
Node node8 = new Node("9");
Node node9 = new Node("1");
root.l = node1;
node1.l = node2;
node2.l = node3;
node2.r = node6;
node3.r = node7;
node7.r = node8;
node6.l = node9;
node3.l = node4;
root.r = node5;
return root;
}
// 节点
static class Node{
// 数据
Object data;
// 左孩子
Node l;
// 右孩子
Node r;
public Node(){}
public Node(Object data) {
this.data = data;
this.l = null;
this.r = null;
}
public Node(Object data, Node l, Node r) {
this.data = data;
this.l = l;
this.r = r;
}
}
}


浙公网安备 33010602011771号