20192304 实验八 《数据结构和面向对象的程序设计》 实验报告
20192304 2020-2021-1 《数据结构与面向对象程序设计》实验五报告
课程:《程序设计与数据结构》
班级: 1923
姓名: 刘润衡
学号:20192304
实验教师:王志强
实验日期:2020年12月3日
必修/选修: 必修
1.实验内容
(1)参考教材PP16.1,完成链树LinkedBinaryTree的实现(getRight,contains,toString,preorder,postorder)
用JUnit或自己编写驱动类对自己实现的LinkedBinaryTree进行测试,提交测试代码运行截图,要全屏,包含自己的学号信息
课下把代码推送到代码托管平台
(2)基于LinkedBinaryTree,实现基于(中序,先序)序列构造唯一一棵二㕚树的功能,比如给出中序HDIBEMJNAFCKGL和先序ABDHIEJMNCFGKL,构造出附图中的树
用JUnit或自己编写驱动类对自己实现的功能进行测试,提交测试代码运行截图,要全屏,包含自己的学号信息
课下把代码推送到代码托管平台
(3)自己设计并实现一颗决策树
提交测试代码运行截图,要全屏,包含自己的学号信息
课下把代码推送到代码托管平台
(4)输入中缀表达式,使用树将中缀表达式转换为后缀表达式,并输出后缀表达式和计算结果(如果没有用树,正常评分。如果用到了树,即使有小的问题,也酌情给满分)
提交测试代码运行截图,要全屏,包含自己的学号信息
2. 实验过程及结果
(1)1参考教材PP16.1,完成链树LinkedBinaryTree的实现(getRight,contains,toString,preorder,postorder)
用JUnit或自己编写驱动类对自己实现的LinkedBinaryTree进行测试,提交测试代码运行截图,要全屏,包含自己的学号信息
课下把代码推送到代码托管平台
2import java.util.Iterator;
public class LinkedBinaryTreeTest {
public static void main(String[] args) {
LinkedBinaryTree num1 = new LinkedBinaryTree("1");
LinkedBinaryTree num2 = new LinkedBinaryTree("9");
LinkedBinaryTree num3 = new LinkedBinaryTree("2");
LinkedBinaryTree num4 = new LinkedBinaryTree("3",num1,num3);
LinkedBinaryTree num5 = new LinkedBinaryTree("0",num2,num4);
LinkedBinaryTree num6 = new LinkedBinaryTree("4",num4,num5);
Iterator it;
System.out.println("right of 8: ");
System.out.println(num4.getRight());
System.out.println("Contains 1? ");
System.out.println(num1.contains("1"));
System.out.println("PreOrder: ");
num6 .toPreString() ;
System.out.println();
System.out.println("PostOrder: ");
num6 .toPostString() ;
System.out.println(num6.toString());
}
}
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedBinaryTree
protected BinaryTreeNode
protected int modCount;
protected LinkedBinaryTree
public LinkedBinaryTree() {
root = null;
}
public LinkedBinaryTree(T element) {
root = new BinaryTreeNode<T>(element);
}
public LinkedBinaryTree(T element, LinkedBinaryTree<T> left,
LinkedBinaryTree<T> right) {
root = new BinaryTreeNode<T>(element);
root.setLeft(left.root);
root.setRight(right.root);
this.left = left;
this.right=right;
}
//调用binarylinktree
public BinaryTreeNode<T> getRootNode() throws EmptyCollectionException {
if (isEmpty()) {
throw new EmptyCollectionException("BinaryTreeNode ");
}
return root;
}
public LinkedBinaryTree<T> getLeft() {
return left;
}
public LinkedBinaryTree<T> getRight() {
return right;
}
public int getHeight()
{
return height(root);
}
//树的深度计算
private int height(BinaryTreeNode<T> node)
{
if(node==null){
return 0;
}
else {
int leftTreeHeight = height(node.getLeft());
int rightTreeHeight= height(node.getRight());
return leftTreeHeight>rightTreeHeight ? (leftTreeHeight+1):(rightTreeHeight+1);
}
}
//获取树根的元素
@Override
public T getRootElement() throws EmptyCollectionException {
if (root.getElement().equals(null)) {
throw new EmptyCollectionException("BinaryTreeNode ");
}
return root.getElement();
}
@Override
public boolean isEmpty() {
return (root == null);
}
@Override
public int size() {
int size = 0;
if(root.getLeft()!=null){
size+=1;
}
if(root.getRight()!=null){
size+=1;
}
return size;
}
//删除右侧结点
public String removeRightSubtree() throws EmptyCollectionException {
if (root == null)
throw new EmptyCollectionException("tree is empty");
BinaryTreeNode cur = root;
while (cur.getLeft() != null){
cur.setRight(null);
cur = cur.left;
}
return super.toString();
}
//删除全部元素
public void removeAllElements() throws EmptyCollectionException {
if (root == null)
throw new EmptyCollectionException("tree is empty");
root = null;
}
//boolean元素查找
@Override
public boolean contains(T targetElement) {
if(targetElement == find(targetElement))
return true;
else
return false;
}
@Override
// 获取当前元素
public T find(T targetElement) {
BinaryTreeNode<T> current = findAgain(targetElement, root);
if (current == null)
try {
throw new ElementNotFoundException("LinkedBinaryTree");
} catch (ElementNotFoundException e) {
e.printStackTrace();
}
return (current.getElement());
}
private BinaryTreeNode<T> findAgain(T targetElement, BinaryTreeNode<T> next) {
if (next == null)
return null;
if (next.getElement().equals(targetElement))
return next;
BinaryTreeNode<T> temp = findAgain(targetElement, next.getLeft());
if (temp == null)
temp = findAgain(targetElement, next.getRight());
return temp;
}
@Override
public Iterator<T> iteratorInOrder() {
ArrayListUnordered<T> tempList = new ArrayListUnordered<T>();
inOrder(root, tempList);
return new TreeIterator(tempList.iterator());
}
public void toPreString(){
preOrder(root);
}
private void preOrder(BinaryTreeNode root){
if(null!= root){
System.out.print(root.getElement() + "\t");
preOrder(root.getLeft());
preOrder(root.getRight());
}
}
public void toPostString(){
postOrder(root);
}
private void postOrder(BinaryTreeNode root) {
if (null != root) {
postOrder(root.getLeft());
postOrder(root.getRight());
System.out.print(root.getElement() + "\t");
}
}
protected void inOrder(BinaryTreeNode<T> node, ArrayListUnordered<T> tempList) {
if (node != null) {
inOrder(node.getLeft(), tempList);
tempList.addToRear(node.getElement());
inOrder(node.getRight(), tempList);
}
}
@Override
public Iterator<T> iteratorPreOrder() {
ArrayListUnordered<T> tempList = new ArrayListUnordered<T>();
preOrder(root, tempList);
return new TreeIterator(tempList.iterator());
}
private void preOrder(BinaryTreeNode<T> node, ArrayListUnordered<T> tempList) {
if (node != null) {
tempList.addToRear(node.getElement());
inOrder(node.getLeft(), tempList);
inOrder(node.getRight(), tempList);
}
}
@Override
public Iterator<T> iteratorPostOrder() {
ArrayListUnordered<T> tempList = new ArrayListUnordered<T>();
postOrder(root, tempList);
return new TreeIterator(tempList.iterator());
}
private void postOrder(BinaryTreeNode<T> node, ArrayListUnordered<T> tempList) {
if (node != null) {
tempList.addToRear(node.getElement());
inOrder(node.getLeft(), tempList);
inOrder(node.getRight(), tempList);
}
}
@Override
public Iterator<T> iteratorLevelOrder() {
ArrayListUnordered<BinaryTreeNode<T>> nodes = new ArrayListUnordered<BinaryTreeNode<T>>();
ArrayListUnordered<T> tempList = new ArrayListUnordered<T>();
BinaryTreeNode<T> current;
nodes.addToRear(root);
while (!nodes.isEmpty()) {
current = nodes.removeFirst();
if (current != null) {
tempList.addToRear(current.getElement());
System.out.println(current.element);
if (current.getLeft() != null)
nodes.addToRear(current.getLeft());
System.out.println(current.left);
if (current.getRight() != null)
nodes.addToRear(current.getRight());
System.out.println(current.right);
} else
tempList.addToRear(null);
}
return new TreeIterator(tempList.iterator());
}
public void toLevelString1(){
if(root == null)
return;
int height = getHeight();
for(int i = 1; i <= height; i++){
levelOrder(root,i);
}
}
private void levelOrder(BinaryTreeNode root,int level){
if(root == null || level < 1){
return;
}
if(level == 1){
System.out.print(root.getElement() + "\n");
return;
}
levelOrder(root.getLeft(),level - 1);
levelOrder(root.getRight(),level - 1);
}
@Override
public Iterator<T> iterator() {
return iteratorInOrder();
}
public String toString() {
UnorderedListADT<BinaryTreeNode<T>> nodes = new ArrayListUnordered<BinaryTreeNode<T>>();
UnorderedListADT<Integer> levelList = new ArrayListUnordered<Integer>();
BinaryTreeNode<T> current;
String result = "";
int Depth = this.getHeight();
int possibleNodes = (int) Math.pow(2, Depth + 1);
int countNodes = 0;
nodes.addToRear(root);
Integer curLevel = 0;
Integer preLevel = -1;
levelList.addToRear(curLevel);
while (countNodes < possibleNodes) {
countNodes = countNodes + 1;
current = nodes.removeFirst();
curLevel = levelList.removeFirst();
if (curLevel > preLevel) {
result = result+ "\n\n";
preLevel = curLevel;
for (int j = 0; j < ((Math.pow(2, (Depth - curLevel))) - 1); j++)
result = result + " ";
} else {
for (int i = 0; i < (Math.pow(2, (Depth - curLevel + 1)) - 1); i++) {
result = result + " ";
}
}
if (current != null) {
result = result + (current.getElement()).toString();
nodes.addToRear(current.getLeft());
levelList.addToRear(curLevel + 1);
nodes.addToRear(current.getRight());
levelList.addToRear(curLevel + 1);
} else {
nodes.addToRear(null);
levelList.addToRear(curLevel + 1);
result = result + " ";
}
}
return result;
}
public void setRight(LinkedBinaryTree<T> right) {
this.right = right;
}
private class TreeIterator implements Iterator<T> {
private int expectedModCount;
private Iterator<T> iter;
public TreeIterator(Iterator<T> iter) {
this.iter = iter;
expectedModCount = modCount;
}
public boolean hasNext() throws ConcurrentModificationException {
if (!(modCount == expectedModCount))
throw new ConcurrentModificationException();
return (iter.hasNext());
}
public T next() throws NoSuchElementException {
if (hasNext())
return (iter.next());
else
throw new NoSuchElementException();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
}
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
public class ArrayIterator
int iteratorModCount;
int current;
public ArrayIterator()
{
iteratorModCount = modCount;
current = 0;
}
public boolean hasNext() throws ConcurrentModificationException
{
return super.iterator().hasNext();
}
public T next() throws ConcurrentModificationException
{
return super.iterator().next();
}
public void remove() throws UnsupportedOperationException
{
throw new UnsupportedOperationException();
}
}
import java.util.Iterator;
public interface BinaryTreeADT
public T getRootElement() throws EmptyCollectionException ;
public boolean isEmpty();
public int size();
public boolean contains(T targetElement);
public T find(T targetElement);
public String toString();
public Iterator<T> iterator();
public Iterator<T> iteratorInOrder();
public Iterator<T> iteratorPreOrder();
public Iterator<T> iteratorPostOrder();
public Iterator<T> iteratorLevelOrder();
}
public class ElementNotFoundException extends RuntimeException
{
public ElementNotFoundException (String collection)
{
super ("The target element is not in this " + collection);
}
}
public interface UnorderedListADT
{
public void addToFront(T element);
public void addToRear(T element);
public void addAfter(T element, T target);
}
public class EmptyCollectionException extends RuntimeException
{
public EmptyCollectionException (String collection)
{
super ("The " + collection + " is empty.");
}
}
import java.util.Iterator;
public interface ListADT
{
public T removeFirst();
public T removeLast();
public T remove(T element);
public T first();
public T last();
public boolean contains(T target);
public boolean isEmpty();
public int size();
public Iterator<T> iterator();
public String toString();
}
public class ArrayListUnordered
@Override
public void addToFront(T element) {
if (size() == list.length)
expandCapacity();
for (int i=rear;i > 0; i--)
list[i] = list[i - 1];
list[0] = element;
rear++;
modCount++;
}
@Override
public void addToRear(T element) {
if (size() == list.length)
expandCapacity();
list[rear] = element;
rear++;
modCount++;
}
@Override
public void addAfter(T element, T target) {
if (size() == list.length)
expandCapacity();
int scan = 0;
//find the insertion point
while (scan < rear && !target.equals(list[scan]))
scan++;
if (scan == rear)
try {
throw new ElementNotFoundException("UnorderedList");
} catch (ElementNotFoundException e) {
e.printStackTrace();
}
scan++;
for (int shilt = rear; shilt > scan; shilt--)
list[shilt] = list[shilt - 1];
list[scan] = element;
rear++;
modCount++;
}
}
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
public abstract class ArrayList
{
private final static int DEFAULT_CAPACITY = 100;
private final static int NOT_FOUND = -1;
protected int rear;
protected T[] list;
protected int modCount;
public ArrayList()
{
this(DEFAULT_CAPACITY);
}
public ArrayList(int initialCapacity)
{
rear = 0;
list = (T[])(new Object[initialCapacity]);
modCount = 0;
}
protected void expandCapacity(){
list = Arrays.copyOf(list,list.length*2);
}
@Override
public T removeLast() throws EmptyCollectionException {
T result = list[rear-1];
list[rear]=null;
rear --;
return result;
}
@Override
public T removeFirst() throws EmptyCollectionException {
T result =list[0];
rear--;
for(int i = 0; i< rear; i++){
list[i] = list[i + 1];
}
list[rear] = null;
return result;
}
@Override
public T remove(T element)
{
T result;
int index = find(element);
if (index == NOT_FOUND)
try {
throw new ElementNotFoundException("ArrayList");
} catch (ElementNotFoundException e) {
e.printStackTrace();
}
result = list[index];
rear--;
for (int scan=index; scan < rear; scan++)
list[scan] = list[scan+1];
list[rear] = null;
modCount++;
return result;
}
@Override
public T first() throws EmptyCollectionException
{
T result = list[0];
return result;
}
@Override
public T last() throws EmptyCollectionException
{
T result = list[rear-1];
return result;
}
@Override
public int size(){
return rear;
}
@Override
public boolean contains(T target)
{
return (find(target) != NOT_FOUND);
}
private int find(T target)
{
int scan = 0;
int result = NOT_FOUND;
if (!isEmpty()) {
while (result == NOT_FOUND && scan < rear)
if (target.equals(list[scan]))
result = scan;
else
scan++;
}
return result;
}
@Override
public boolean isEmpty(){
if(size() == 0){
return true;
}else
return false;
}
@Override
public String toString(){
String string = "";
for (int i = 0;i < rear;i++){
string += list[i] + " ";
}
return string;
}
@Override
public Iterator<T> iterator(){
return new ArrayListIterator();
}
private class ArrayListIterator implements Iterator<T>
{
int iteratorModCount;
int current;
public ArrayListIterator()
{
iteratorModCount = modCount;
current = 0;
}
@Override
public boolean hasNext() throws ConcurrentModificationException
{
if (iteratorModCount != modCount)
throw new ConcurrentModificationException();
return (current < rear);
}
@Override
public T next() throws ConcurrentModificationException
{
if (!hasNext())
throw new NoSuchElementException();
current++;
return list[current - 1];
}
@Override
public void remove() throws UnsupportedOperationException
{
throw new UnsupportedOperationException();
}
}
}
public class BinaryTreeNode
protected T element;
protected BinaryTreeNode<T> left;
protected BinaryTreeNode<T> right;
public BinaryTreeNode(T obj) {
this.element = obj;
this.left = null;
this.right = null;
}
public BinaryTreeNode(T obj, LinkedBinaryTree<T> left,
LinkedBinaryTree<T> right)throws EmptyCollectionException {
element = obj;
if (left == null)
this.left = null;
else
this.left = left.getRootNode();
if (right == null)
this.right = null;
else
this.right = right.getRootNode();
}
public int numChildren() {
int children = 0;
if (left != null)
children = 1 + left.numChildren();
if (right != null)
children = children + 1 + right.numChildren();
return children;
}
public T getElement() {
return element;
}
public BinaryTreeNode<T> getRight() {
return right;
}
public void setRight(BinaryTreeNode<T> node) {
right = node;
}
public BinaryTreeNode<T> getLeft() {
return left;
}
public void setLeft(BinaryTreeNode<T> node) {
left = node;
}
public boolean judge(){
if(right == null && left == null)
return true;
else
return false;
}
}
(2)1基于LinkedBinaryTree,实现基于(中序,先序)序列构造唯一一棵二㕚树的功能,比如给出中序HDIBEMJNAFCKGL和先序ABDHIEJMNCFGKL,构造出附图中的树
用JUnit或自己编写驱动类对自己实现的功能进行测试,提交测试代码运行截图,要全屏,包含自己的学号信息
2import java.util.Scanner;
import java.util.StringTokenizer;
public class CreateTree {
public LinkedBinaryTree
LinkedBinaryTree
if(inorder.length == preorder.length && inorder.length != 0 && preorder.length != 0){
int n = 0;
while (!inorder[n].equals(preorder[0])) {
n++;
}
String[] preLeft = new String[n];
String[] inLeft = new String[n];
String[] preRight = new String[preorder.length - n - 1];
String[] inRight = new String[inorder.length - n - 1];
for (int t = 0; t < inorder.length; t++) {
if (t < n) {
preLeft[t] = preorder[t + 1];
inLeft[t] = inorder[t];
}
if (t > n) {
preRight[t - n - 1] = preorder[t];
inRight[t - n - 1] = inorder[t];
}
if(t == n){//
continue;
}
}
LinkedBinaryTree
LinkedBinaryTree
binaryTree = new LinkedBinaryTree
}else
{
binaryTree = new LinkedBinaryTree<>();
}
return binaryTree;
}
public static void main(String[] args)
{
String a,b;
int i = 0,j = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Input the PreOrder:");
a = scanner.nextLine();
System.out.println("Input the PostOrder:");
b = scanner.nextLine();
StringTokenizer str1 = new StringTokenizer(a, " ");
StringTokenizer str2= new StringTokenizer(b, " ");
String[] string1 = new String[str1.countTokens()];
String[] string2 = new String[str2.countTokens()];
while (str1.hasMoreTokens())
{
string1[i] = str1.nextToken();
i++;
}
while (str2.hasMoreTokens())
{
string2[j] = str2.nextToken();
j++;
}
CreateTree ct = new CreateTree();
LinkedBinaryTree<String> binaryTree = ct.CreatTree(string2,string1);
System.out.println("The Tree is:");
System.out.println();
System.out.println(binaryTree.toString());
}
}
(3)1自己设计并实现一颗决策树
提交测试代码运行截图,要全屏,包含自己的学号信息
课下把代码推送到代码托管平台
2import java.util.Scanner;
public class PsychologicalTest
{
private LinkedBinaryTree
public PsychologicalTest()
{
String e1 = "你知道我是谁吗 ?";
String e2 = "你知道你是谁吗 ?";
String e3 = "你知道我父亲是谁吗 ?";
String e4 = "你有对象吗 ?";
String e5 = "你是单身狗吗?";
String e6 = "你吃过汉堡吗 ?";
String e7 = "你学历是大学吗 ?";
String e8 = "同道单身狗";
String e9 = "咱俩无话可聊";
String e10 = "好好努力嗷";
String e11 = "大户人家";
String e12 = "祝你早日毕业";
String e13 = "可以";
String e14 = "害";
String e15 ="我懂你的";
LinkedBinaryTree<String> n2, n3, n4, n5, n6, n7, n8, n9,
n10, n11, n12, n13,n14,n15;
n8 = new LinkedBinaryTree<String>(e8);
n9 = new LinkedBinaryTree<String>(e9);
n4 = new LinkedBinaryTree<String>(e4, n8, n9);
n10 = new LinkedBinaryTree<String>(e10);
n11 = new LinkedBinaryTree<String>(e11);
n5 = new LinkedBinaryTree<String>(e5, n10, n11);
n12 = new LinkedBinaryTree<String>(e12);
n13 = new LinkedBinaryTree<String>(e13);
n6 = new LinkedBinaryTree<String>(e6, n12, n13);
n14 = new LinkedBinaryTree<String>(e14);
n15 = new LinkedBinaryTree<String>(e15);
n7 = new LinkedBinaryTree<String>(e7,n14,n15);
n2 = new LinkedBinaryTree<String>(e2, n4, n5);
n3 = new LinkedBinaryTree<String>(e3, n6, n7);
tree = new LinkedBinaryTree<String>(e1, n2, n3);
}
public void start()
{
Scanner scan = new Scanner(System.in);
LinkedBinaryTree<String> current = tree;
System.out.println ("让我们聊一聊");
while (current.size() > 1)
{
System.out.println (current.getRootElement());
if (scan.nextLine().equalsIgnoreCase("N"))
current = current.getLeft();
else
current = current.getRight();
}
System.out.println (current.getRootElement());
}
public static void main(String[] args){
PsychologicalTest test = new PsychologicalTest();
test.start();
}
}
(4)1输入中缀表达式,使用树将中缀表达式转换为后缀表达式,并输出后缀表达式和计算结果(如果没有用树,正常评分。如果用到了树,即使有小的问题,也酌情给满分)
提交测试代码运行截图,要全屏,包含自己的学号信息
2
import java.util.Scanner;
public class FixTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("请输入表达式:");
String s = scan.nextLine();
Fix fix = new Fix();
System.out.println("后缀表达式为:\n"+Fix.getrp(s));
System.out.println("计算结果为:\n"+fix.calrp(Fix.getrp(s)));
}
}
import java.util.Stack;
public class Fix {
static Stack
public static Float getv(char op, Float f1, Float f2) {
if (op == '+') return f2 + f1;
else if (op == '-') return f2 - f1;
else if (op == '*') return f2 * f1;
else if (op == '/') return f2 / f1;
else return Float.valueOf(-0);
}
public static float calrp(String rp) {
Stack<Float> v = new Stack<>();
char[] arr = rp.toCharArray();
int len = arr.length;
for (int i = 0; i < len; i++) {
Character ch = arr[i];
if (ch >= '0' && ch <= '9') v.push(Float.valueOf(ch - '0'));
else v.push(getv(ch, v.pop(), v.pop()));
}
return v.pop();
}
public static String getrp(String s) {
char[] arr = s.toCharArray();
int len = arr.length;
String out = "";
for (int i = 0; i < len; i++) {
char ch = arr[i];
if (ch == ' ') continue;
if (ch >= '0' && ch <= '9') {
out += ch;
continue;
}
if (ch == '(')
op.push(ch);
if (ch == '+' || ch == '-') {
while (!op.empty() && (op.peek() != '('))
out += op.pop();
op.push(ch);
continue;
}
if (ch == '*' || ch == '/') {
while (!op.empty() && (op.peek() == '*' || op.peek() == '/'))
out += op.pop();
op.push(ch);
continue;
}
if (ch == ')') {
while (!op.empty() && op.peek() != '(')
out += op.pop();
op.pop();
continue;
}
}
while (!op.empty()) out += op.pop();
return out;
}
}
3. 实验过程中遇到的问题和解决过程
(1)无法正确显示问题文字;需要将所有相关的代码全部换成GBK编码。
(2)程序需要对接口的调用,需要将相关接口以及程序放在同一个包之中。
其他(感悟、思考等)
树的实现相对于其他方式在连续输出时不易显示出逻辑顺序。
树的实现更多是是一种对于编程者的解决方案,面对用户时输出成树的形状更加的明显易懂。
树在输出树形状后简洁明了。