# 20192304 2020-2021-1 《数据结构与面向对象程序设计》实验五报告

## 1.实验内容

（3）自己设计并实现一颗决策树

（4）输入中缀表达式，使用树将中缀表达式转换为后缀表达式，并输出后缀表达式和计算结果（如果没有用树，正常评分。如果用到了树，即使有小的问题，也酌情给满分）

## 2. 实验过程及结果

2import java.util.Iterator;

public static void main(String[] args) {

    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;

protected BinaryTreeNode root;//设置根结点
protected int modCount;

public LinkedBinaryTree() {
root = null;
}

root = new BinaryTreeNode<T>(element);
}

root = new BinaryTreeNode<T>(element);
root.setLeft(left.root);
root.setRight(right.root);
this.left = left;

this.right=right;
}

public BinaryTreeNode<T> getRootNode() throws EmptyCollectionException {
if (isEmpty()) {
throw new EmptyCollectionException("BinaryTreeNode ");
}
return root;
}

return left;
}

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 {
} 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);
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) {
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) {
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;

while (!nodes.isEmpty()) {
current = nodes.removeFirst();

if (current != null) {
System.out.println(current.element);
if (current.getLeft() != null)
System.out.println(current.left);
if (current.getRight() != null)
System.out.println(current.right);
} else
}

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() {

BinaryTreeNode<T> current;
String result = "";
int Depth = this.getHeight();
int possibleNodes = (int) Math.pow(2, Depth + 1);
int countNodes = 0;

Integer curLevel = 0;
Integer preLevel = -1;

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();
} else {
result = result + " ";
}
}
return result;
}

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 extends ArrayList implements Iterator {

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 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 void addToFront(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 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 extends ArrayList implements UnorderedListADT {
@Override
if (size() == list.length)
expandCapacity();
for (int i=rear;i > 0; i--)
list[i] = list[i - 1];
list[0] = element;
rear++;
modCount++;
}

@Override
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 implements ListADT, Iterable
{
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;
}

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;
}


}

2import java.util.Scanner;
import java.util.StringTokenizer;

public class CreateTree {
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;
}
}
binaryTree = new LinkedBinaryTree(preorder[0], left, right);
}else
{
}
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();
System.out.println("The Tree is：");
System.out.println();
System.out.println(binaryTree.toString());
}


}

(3)1自己设计并实现一颗决策树

2import java.util.Scanner;

public class PsychologicalTest
{

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;

n4 = new LinkedBinaryTree<String>(e4, n8, n9);

n5 = new LinkedBinaryTree<String>(e5, n10, n11);

n6 = new LinkedBinaryTree<String>(e6, n12, n13);

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);

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 op = new 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）程序需要对接口的调用，需要将相关接口以及程序放在同一个包之中。

## 参考资料

posted @ 2020-12-08 21:00  20192304刘润衡  阅读(103)  评论(0编辑  收藏  举报