20202309葛鹏宇《数据结构与面向对象程序设计》实验8实验报告

# 学号20202309  2021-2022-1 《数据结构与面向对象程序设计》实验8报告

课程:《程序设计与数据结构》
班级: 2023
姓名: 葛鹏宇
学号:20202309
实验教师:王志强
实验日期:2021年11月18日
必修/选修: 必修

## 1.实验内容

    1. 参考教材PP16.1,完成链树LinkedBinaryTree的实现(getRight,contains,toString,preorder,postorder)
      用JUnit或自己编写驱动类对自己实现的LinkedBinaryTree进行测试,提交测试代码运行截图,要全屏,包含自己的学号信息
      课下把代码推送到代码托管平台

    2. 基于LinkedBinaryTree,实现基于(中序,先序)序列构造唯一一棵二㕚树的功能,比如给出中序HDIBEMJNAFCKGL和后序ABDHIEJMNCFGKL,构造出附图中的树
      用JUnit或自己编写驱动类对自己实现的功能进行测试,提交测试代码运行截图,要全屏,包含自己的学号信息
      课下把代码推送到代码托管平台

    3. 自己设计并实现一颗决策树
      提交测试代码运行截图,要全屏,包含自己的学号信息
      课下把代码推送到代码托管平台

    4. 输入中缀表达式,使用树将中缀表达式转换为后缀表达式,并输出后缀表达式和计算结果(如果没有用树,正常评分。如果用到了树,即使有小的问题,也酌情给满分)
      提交测试代码运行截图,要全屏,包含自己的学号信息



## 2. 实验过程及结果

码云:gpy/gpy20202309 - Gitee.com

    1. 参考教材PP16.1,完成链树LinkedBinaryTree的实现(getRight,contains,toString,preorder,postorder)
      用JUnit或自己编写驱动类对自己实现的LinkedBinaryTree进行测试,提交测试代码运行截图,要全屏,包含自己的学号信息
      课下把代码推送到代码托管平台

 

 

 

import  java.util.*;
public class LinkedBinaryTree<T>
{
    protected BTNode<T> root;

    public LinkedBinaryTree()
    {
        root = null;
    }

    public LinkedBinaryTree (T element)
    {
        root = new BTNode<T>(element);
    }

    public LinkedBinaryTree (T element, LinkedBinaryTree<T> left,
                             LinkedBinaryTree<T> right)
    {
        root = new BTNode<T>(element);
        root.setLeft(left.root);
        root.setRight(right.root);
    }

    public T getRootElement() throws Exception, EmptyCollectionException {
        if (root == null)
            throw new EmptyCollectionException ("Get root operation "
                    + "failed. The tree is empty.");

        return root.getElement();
    }

    public LinkedBinaryTree<T> getLeft() throws Exception, EmptyCollectionException {
        if (root == null)
            throw new EmptyCollectionException ("Get left operation "
                    + "failed. The tree is empty.");

        LinkedBinaryTree<T> result = new LinkedBinaryTree<T>();
        result.root = root.getLeft();

        return result;
    }

    public T find (T target) throws ElementNotFoundException {
        BTNode<T> node = null;

        if (root != null)
            node = root.find(target);

        if (node == null)
            throw new ElementNotFoundException("Find operation failed. "
                    + "No such element in tree.");

        return node.getElement();
    }

    //返回大小
    public int size()
    {
        int result = 0;

        if (root != null)
            result = root.count();

        return result;
    }

    public LinkedBinaryTree<T> getRight() throws Exception, EmptyCollectionException {
        if (root == null)
            throw new EmptyCollectionException ("Get left operation "
                    + "failed. The tree is empty.");

        LinkedBinaryTree<T> result = new LinkedBinaryTree<T>();
        result.root = root.getRight();

        return result;
    }

    public boolean contains (T target) {
        if (root.find(target)==null){
            return false;
        }
        else {
            return true;
        }
    }

    public boolean isEmpty() {
        if (root==null){
            return true;
        }
        else {
            return false;
        }
    }

    //先序遍历
    public ArrayList<T> preorder() {
        ArrayList<T> iter = new ArrayList<T>();

        if (root != null)
            root.preorder (iter);

        return iter;
    }

    //后续遍历
    public ArrayList<T> postorder(BTNode<Character> root) {
        ArrayList<T> iter = new ArrayList<T>();

        if (this.root != null)
            this.root.postorder (iter);

        return iter;
    }
    public String toString() {
        return super.toString();
    }
import java.util.ArrayList;
import java.util.Iterator;

public interface BinaryTree<T> extends Iterable<T>
{
    public T getRootElement() throws  Exception;

    public BinaryTree<T> getLeft() throws  Exception;

    public BinaryTree<T> getRight() throws Exception;

    public boolean contains (T target) throws Exception;

    public T find (T target) throws  Exception;

    public boolean isEmpty();

    public int size();

    public String toString();

    public ArrayList<T> preorder();

    public Iterator<T> inorder();

    public ArrayList<T> postorder();

    public Iterator<T> levelorder() throws Exception, EmptyCollectionException;
}
import java.util.ArrayList;
public class BTNode<T>
{
    protected T element;
    protected BTNode<T> left, right;
    public BTNode(T element)
    {
        this.element = element;
        left = right = null;
    }
    public T getElement()
    {
        return element;
    }
    public void setElement (T element)
    {
        this.element = element;
    }
    public BTNode<T> getLeft()
    {
        return left;
    }
    public void setLeft (BTNode<T> left)
    {
        this.left = left;
    }
    public BTNode<T> getRight()
    {
        return right;
    }
    public void setRight (BTNode<T> right)
    {
        this.right = right;
    }
    public BTNode<T> find (T target) {
        BTNode<T> result = null;
        if (element.equals(target))
            result = this;
        else
        {
            if (left != null)
                result = left.find(target);
            if (result == null && right != null)
                result = right.find(target);
        }
        return result;
    }
    public int count() {
        int result = 1;
        if (left != null)
            result += left.count();
        if (right != null)
            result += right.count();
        return result;
    }
    public void inorder (ArrayList<T> iter) {
        if (left != null)
            left.inorder (iter);
        iter.add (element);
        if (right != null)
            right.inorder (iter);
    }
    public void preorder (ArrayList<T> iter) {
        iter.add (element);
        if (left != null)
            left.inorder (iter);
        if (right != null)
            right.inorder (iter);
    }
    public void postorder (ArrayList<T> iter) {
        if (left != null)
            left.inorder (iter);
        if (right != null)
            right.inorder (iter);
        iter.add (element);
    }
}

 

2、基于LinkedBinaryTree,实现基于(中序,先序)序列构造唯一一棵二㕚树的功能,比如给出中序HDIBEMJNAFCKGL和后序ABDHIEJMNCFGKL,构造出附图中的树用JUnit或自己编写驱动类对自己实现的功能进行测试,提交测试代码运行截图,要全屏,包含自己的学号信息课下把代码推送到代码托管平台

 

 

import  java.util.*;
public class LinkedBinaryTree<T>
{
    protected BTNode<T> root;

    public LinkedBinaryTree()
    {
        root = null;
    }

    public LinkedBinaryTree (T element)
    {
        root = new BTNode<T>(element);
    }

    public LinkedBinaryTree (T element, LinkedBinaryTree<T> left,
                             LinkedBinaryTree<T> right)
    {
        root = new BTNode<T>(element);
        root.setLeft(left.root);
        root.setRight(right.root);
    }

    public T getRootElement() throws Exception, EmptyCollectionException {
        if (root == null)
            throw new EmptyCollectionException ("Get root operation "
                    + "failed. The tree is empty.");

        return root.getElement();
    }

    public LinkedBinaryTree<T> getLeft() throws Exception, EmptyCollectionException {
        if (root == null)
            throw new EmptyCollectionException ("Get left operation "
                    + "failed. The tree is empty.");

        LinkedBinaryTree<T> result = new LinkedBinaryTree<T>();
        result.root = root.getLeft();

        return result;
    }

    public T find (T target) throws ElementNotFoundException {
        BTNode<T> node = null;

        if (root != null)
            node = root.find(target);

        if (node == null)
            throw new ElementNotFoundException("Find operation failed. "
                    + "No such element in tree.");

        return node.getElement();
    }

    //返回大小
    public int size()
    {
        int result = 0;

        if (root != null)
            result = root.count();

        return result;
    }

    public LinkedBinaryTree<T> getRight() throws Exception, EmptyCollectionException {
        if (root == null)
            throw new EmptyCollectionException ("Get left operation "
                    + "failed. The tree is empty.");

        LinkedBinaryTree<T> result = new LinkedBinaryTree<T>();
        result.root = root.getRight();

        return result;
    }

    public boolean contains (T target) {
        if (root.find(target)==null){
            return false;
        }
        else {
            return true;
        }
    }

    public boolean isEmpty() {
        if (root==null){
            return true;
        }
        else {
            return false;
        }
    }

    //先序遍历
    public ArrayList<T> preorder() {
        ArrayList<T> iter = new ArrayList<T>();

        if (root != null)
            root.preorder (iter);

        return iter;
    }

    //后续遍历
    public ArrayList<T> postorder(BTNode<Character> root) {
        ArrayList<T> iter = new ArrayList<T>();

        if (this.root != null)
            this.root.postorder (iter);

        return iter;
    }
    public String toString() {
        return super.toString();
    }

    public int findIndexInArray(char[] a, char x, int begin, int end) {
        for(int i=begin;i<=end;i++) {
            if(a[i] == x) {
                return i;
            }
        }
        return -1;
    }

    public void initTree(char[] preOrder, char[] inOrder) {
        this.root = this.initTree(preOrder, 0, preOrder.length-1, inOrder, 0, inOrder.length-1);
    }

    public BTNode initTree(char[] preOrder, int start1, int end1, char[] inOrder, int start2, int end2) {
        if(start1 > end1 || start2 > end2) {
            return null;
        }
        //通过前序找到根结底
        char rootData = preOrder[start1];
        BTNode<Character> head = new BTNode(rootData);
        int rootIndex = findIndexInArray(inOrder, rootData, start2, end2);
        int offSet = rootIndex - start2 - 1;
        //左子树
        BTNode left = initTree(preOrder, start1+1, start1+1+offSet, inOrder, start2, start2+offSet);
        //右子树
        BTNode right = initTree(preOrder, start1+offSet+2, end1, inOrder, rootIndex+1, end2);
        head.left = left;
        head.right = right;
        return head;
    }
}

 

3、自己设计并实现一颗决策树
提交测试代码运行截图,要全屏,包含自己的学号信息
课下把代码推送到代码托管平台

 

 

import java.util.Scanner;

public class DecisionTree {
    private LinkedBinaryTree<String> tree;

    public DecisionTree(){
        String e1 = "Do you have homework?";
        String e2 = "Do you have any difficulties in study?";
        String e3 = "Are you always hungry?";
        String e4 = "Is it difficult for you to get up?";
        String e5 = "Do you often exercise?";
        String e6 = "Do you like study Java?";
        String e7 = "thank you";
        String e8 = "thank you";
        String e9 = "thank you";
        String e10 = "thank you";
        String e11 = "thank you";
        String e12 = "pass!";
        String e13 = "fail!!!";

        LinkedBinaryTree<String> n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,n13;
        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);
        n7 = new LinkedBinaryTree<String>(e7);
        n2 = new LinkedBinaryTree<String>(e2,n4,n5);
        n3 = new LinkedBinaryTree<String>(e3,n6,n7);

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

    public void diagnose() throws Exception {
        Scanner scan = new Scanner(System.in);
        LinkedBinaryTree<String> current = tree;

        System.out.println("some questions:");
        while(current.size()>1)
        {
            System.out.println(current.getRootElement());
            if(scan.nextLine().equalsIgnoreCase("Y"))
                current = current.getLeft();
            else
                current = current.getRight();
        }
        System.out.println(current.getRootElement());
    }
}

4、输入中缀表达式,使用树将中缀表达式转换为后缀表达式,并输出后缀表达式和计算结果(如果没有用树,正常评分。如果用到了树,即使有小的问题,也酌情给满分)
提交测试代码运行截图,要全屏,包含自己的学号信息

 

 

 

 

import java.util.Stack;
public class Reverse {
    static Stack<Character> op = new Stack<>();
    public static Float getv(char op, Float f1, Float f2) {
        if (op == '+')
            return f1 + f2;
        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 cal(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 get(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:第二个实验题目给我带来了挺大的困难,就是想不出构造要求的那个二叉树的逻辑是什么。

 - 问题1解决方案:在网上查阅资料,参考了别人的想法。


## 其他(感悟、思考等)
这次实验是关于树的实验,有很多名词的概念我还没有掌握理解得十分到位,像先序后序等等具体是怎么实现的我有些遗忘,网上查找资料后才弄清楚。数据结构中确实很多词需要真正理解它的内在变换过程才能在写代码时明白逻辑,减少思考负担。


## 参考资料

-  [《Java程序设计与数据结构教程(第4版)》]

posted @ 2021-11-28 21:46  20202309葛鹏宇  阅读(10)  评论(0编辑  收藏  举报