20192314 2020—2021—1 《数据结构与面向对象程序设计》实验八 树

1.参考教材PP16.1,完成链树LinkedBinaryTree的实现(getRight,contains,toString,preorder,postorder)

用JUnit或自己编写驱动类对自己实现的LinkedBinaryTree进行测试,提交测试代码运行截图,要全屏,包含自己的学号信息

课下把代码推送到代码托管平台

程序代码

LinkedBinaryTree

import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedBinaryTree implements Iterable, BinaryTreeADT {
protected BinaryTreeNode root;//设置根结点
protected int modCount;
protected LinkedBinaryTree left,right;
public LinkedBinaryTree() {
root = null;
}

public LinkedBinaryTree(T element) {
root = new BinaryTreeNode(element);
}

public LinkedBinaryTree(T element, LinkedBinaryTree left,
LinkedBinaryTree right) {
root = new BinaryTreeNode(element);
root.setLeft(left.root);
root.setRight(right.root);
this.left = left;

this.right=right;
}

//调用binarylinktree
public BinaryTreeNode getRootNode() throws EmptyCollectionException {
if (isEmpty()) {
throw new EmptyCollectionException("BinaryTreeNode ");
}
return root;
}

public LinkedBinaryTree getLeft() {
return left;
}

public LinkedBinaryTree getRight() {
return right;
}

public int getHeight()
{
return height(root);
}

//树的深度计算
private int height(BinaryTreeNode 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 current = findAgain(targetElement, root);

if (current == null)
try {
throw new ElementNotFoundException("LinkedBinaryTree");
} catch (ElementNotFoundException e) {
e.printStackTrace();
}

return (current.getElement());
}

private BinaryTreeNode findAgain(T targetElement, BinaryTreeNode next) {
if (next == null)
return null;

if (next.getElement().equals(targetElement))
return next;
// 运用递归进行子树的查找
BinaryTreeNode temp = findAgain(targetElement, next.getLeft());

if (temp == null)
temp = findAgain(targetElement, next.getRight());

return temp;
}

//中序输出
@Override
public Iterator iteratorInOrder() {
ArrayListUnordered tempList = new ArrayListUnordered();
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 node, ArrayListUnordered tempList) {
if (node != null) {
inOrder(node.getLeft(), tempList);
tempList.addToRear(node.getElement());
inOrder(node.getRight(), tempList);
}
}

//运用递归方法的前序查找
@Override
public Iterator iteratorPreOrder() {
ArrayListUnordered tempList = new ArrayListUnordered();
preOrder(root, tempList);
return new TreeIterator(tempList.iterator());
}
private void preOrder(BinaryTreeNode node, ArrayListUnordered tempList) {
if (node != null) {
tempList.addToRear(node.getElement());
inOrder(node.getLeft(), tempList);
inOrder(node.getRight(), tempList);
}
}
//运用迭代方法的后序查找
@Override
public Iterator iteratorPostOrder() {
ArrayListUnordered tempList = new ArrayListUnordered();
postOrder(root, tempList);
return new TreeIterator(tempList.iterator());
}
private void postOrder(BinaryTreeNode node, ArrayListUnordered tempList) {
if (node != null) {
tempList.addToRear(node.getElement());
inOrder(node.getLeft(), tempList);
inOrder(node.getRight(), tempList);
}
}

//递归方法的层序遍历
@Override
public Iterator iteratorLevelOrder() { //递归方法的层序遍历
ArrayListUnordered<BinaryTreeNode> nodes = new ArrayListUnordered<BinaryTreeNode>();
ArrayListUnordered tempList = new ArrayListUnordered();
BinaryTreeNode 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 iterator() {
return iteratorInOrder();
}

public String toString() {
UnorderedListADT<BinaryTreeNode> nodes = new ArrayListUnordered<BinaryTreeNode>();
UnorderedListADT levelList = new ArrayListUnordered();

BinaryTreeNode 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 right) {
this.right = right;
}

private class TreeIterator implements Iterator {
private int expectedModCount;
private Iterator iter;

//迭代
public TreeIterator(Iterator 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();
}
}

}

BinaryTreeADT

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

public Iterator iteratorInOrder();

public Iterator iteratorPreOrder();

public Iterator iteratorPostOrder();

public Iterator iteratorLevelOrder();

}

LinkedBinaryTreeTest

import java.util.Iterator;

public class LinkedBinaryTreeTest {
public static void main(String[] args) {
LinkedBinaryTree num1 = new LinkedBinaryTree("2");
LinkedBinaryTree num2 = new LinkedBinaryTree("0");
LinkedBinaryTree num3 = new LinkedBinaryTree("1");
LinkedBinaryTree num4 = new LinkedBinaryTree("8",num1,num3);
LinkedBinaryTree num5 = new LinkedBinaryTree("3",num2,num4);
LinkedBinaryTree num6 = new LinkedBinaryTree("0",num4,num5);

Iterator it;
System.out.println("right of 8: ");
System.out.println(num4.getRight());
System.out.println("Contains 2? ");
System.out.println(num1.contains("2"));

System.out.println("PreOrder: ");
num6 .toPreString() ;

System.out.println();

System.out.println("PostOrder: ");
num6 .toPostString() ;

System.out.println(num6.toString());

}
}

EmptyCollectionException

public class EmptyCollectionException extends RuntimeException
{

public EmptyCollectionException (String collection)
{
super ("The " + collection + " is empty.");
}
}

UnorderedListADT

public interface UnorderedListADT extends ListADT
{

public void addToFront(T element);

public void addToRear(T element);

public void addAfter(T element, T target);
}

ElementNotFoundException

public class ElementNotFoundException extends RuntimeException
{
public ElementNotFoundException (String collection)
{
super ("The target element is not in this " + collection);
}
}

ListADT

import java.util.Iterator;
public interface ListADT extends Iterable
{
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 iterator();
public String toString();
}

ArrayIterator

import java.util.ArrayList;
//使用iterator遍历集合的同时对集合进行修改就会出现java.util.ConcurrentModificationException异常
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();
}
}

ArrayListUnordered

public class ArrayListUnordered extends ArrayList implements UnorderedListADT {
@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++;
}

}

ArrayList

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 iterator(){
return new ArrayListIterator();
}

private class ArrayListIterator implements Iterator
{
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();
}

}

}

BinaryTreeNode

public class BinaryTreeNode {

protected T element;
protected BinaryTreeNode left;
protected BinaryTreeNode right;

public BinaryTreeNode(T obj) {
this.element = obj;
this.left = null;
this.right = null;
}

///合并构建声明
public BinaryTreeNode(T obj, LinkedBinaryTree left,
LinkedBinaryTree 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 getRight() {
return right;
}

public void setRight(BinaryTreeNode node) {
right = node;
}

public BinaryTreeNode getLeft() {
return left;
}

public void setLeft(BinaryTreeNode node) {
left = node;
}

public boolean judge(){
if(right == null && left == null)
//叶结点的左侧和右侧都没有结点
return true;
else
return false;
}

}

运行截图


基于LinkedBinaryTree,实现基于(中序,先序)序列构造唯一一棵二㕚树的功能,比如给出中序HDIBEMJNAFCKGL和###后序ABDHIEJMNCFGKL,构造出附图中的树

用JUnit或自己编写驱动类对自己实现的功能进行测试,提交测试代码运行截图,要全屏,包含自己的学号信息

课下把代码推送到代码托管平台

程序代码

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

public class CreateTree {
public LinkedBinaryTree CreatTree(String inorder[],String preorder[]){
LinkedBinaryTree binaryTree = null;
if(inorder.length == preorder.length && inorder.length != 0 && preorder.length != 0){
int n = 0;
//根据前序遍历第一个root 进行中序遍历
while (!inorder[n].equals(preorder[0])) {
n++;
}
//根据前序遍历第一个root 进行中序遍历
//左子树的数组输入
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 left = CreatTree(inLeft, preLeft);
LinkedBinaryTree right = CreatTree(inRight, preRight);
binaryTree = new LinkedBinaryTree(preorder[0], left, right);//树的输出
// System.out.println(binaryTree.toString());*/
LinkedBinaryTree left = CreatTree(inLeft, preLeft);
LinkedBinaryTree right = CreatTree(inRight, preRight);
binaryTree = new LinkedBinaryTree(preorder[0], left, right);//树的输出
// System.out.println(binaryTree.toString());
}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();e(string2,string1);
System.out.println("The Tree is:");
j++;
}

//中序输出
//前序输出
CreateTree ct = new CreateTree();
LinkedBinaryTree binaryTree = ct.CreatTre
System.out.println();
System.out.println(binaryTree.toString());
}
}

运行截图

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

提交测试代码运行截图,要全屏,包含自己的学号信息

课下把代码推送到代码托管平台

程序代码

import java.util.Scanner;

public class PsychologicalTest
{
private LinkedBinaryTree tree;

public PsychologicalTest()
{
String e1 = "你玩CSGO吗 ?";
String e2 = "你玩崩坏三吗 ?";
String e3 = "你经常打竞技排位吗 ?";
String e4 = "你有对象吗 ?";
String e5 = "你氪金了吗 ?";
String e6 = "你喜欢打仓库图吗 ?";
String e7 = "你的段位达到了大地球吗 ?";
String e8 = "同道单身狗";
String e9 = "咱俩无话可聊";
String e10 = "穷鬼";
String e11 = "大户人家";
String e12 = "祝你早日登上大地球";
String e13 = "nt";
String e14 = "废物";
String e15 ="精神小伙";

LinkedBinaryTree n2, n3, n4, n5, n6, n7, n8, n9,
n10, n11, n12, n13,n14,n15;

n8 = new LinkedBinaryTree(e8);
n9 = new LinkedBinaryTree(e9);
n4 = new LinkedBinaryTree(e4, n8, n9);

n10 = new LinkedBinaryTree(e10);
n11 = new LinkedBinaryTree(e11);
n5 = new LinkedBinaryTree(e5, n10, n11);

n12 = new LinkedBinaryTree(e12);
n13 = new LinkedBinaryTree(e13);
n6 = new LinkedBinaryTree(e6, n12, n13);

n14 = new LinkedBinaryTree(e14);
n15 = new LinkedBinaryTree(e15);
n7 = new LinkedBinaryTree(e7,n14,n15);

n2 = new LinkedBinaryTree(e2, n4, n5);
n3 = new LinkedBinaryTree(e3, n6, n7);

tree = new LinkedBinaryTree(e1, n2, n3);
}

public void start()
{
Scanner scan = new Scanner(System.in);
LinkedBinaryTree 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();

}

}

运行截图

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

提交测试代码运行截图,要全屏,包含自己的学号信息

程序代码

FixTest

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

Fix

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

运行截图

实验心得

问题1:子树无法通过链表方式与根节点相连接。

问题1解决方案:
将节点的定义方式更改,从下往上定义节点,在根节点处定义时直接将左右两个子树的根节点连接在根节点上。

问题2:在写决策树时,一开始没有仔细学习,就看了一下老师的决策树代码和简单的听了听,结果写的时候根本写不出来

问题2解决方案:乱写了几次实验后,我意识到自己就这么写确实写不出来,于是我重新看了看有关决策树的博客,并请教了同学,才实现了决策树。

posted @ 2020-12-09 22:00  √子非鱼  阅读(170)  评论(0)    收藏  举报