标签:遍历 unit info htm mic 使用 中缀 日期 null
课程:《程序设计与数据结构》
班级: 1823
姓名: 盛国榕
学号:20182332
实验教师:王志强
实验日期:2019年10月28日
必修/选修: 必修
输入中缀表达式,使用树将中缀表达式转换为后缀表达式,并输出后缀表达式和计算结果(如果没有用树,正常评分。如果用到了树,即使有小的问题,也酌情给满分)
链树的实现:
getRight |
---|
public LinkedBinaryTree<T> getRight()
{
LinkedBinaryTree node = new LinkedBinaryTree();
node.root=root.getRight();
// return new LinkedBinaryTree(root.getRight());
return node;
}
contains |
---|
public boolean contains(T targetElement)
{
if (find(targetElement)==targetElement){
return true;
}
else {
return false;
}
}
public T find(T targetElement) throws ElementNotFoundException
{
BinaryTreeNode<T> current = findNode(targetElement, root);
if (current == null)
throw new ElementNotFoundException("LinkedBinaryTree");
return (current.getElement());
}
private BinaryTreeNode<T> findNode(T targetElement,
BinaryTreeNode<T> next)
{
if (next == null)
return null;
if (next.getElement().equals(targetElement))
return next;
BinaryTreeNode<T> temp = findNode(targetElement, next.getLeft());
if (temp == null)
temp = findNode(targetElement, next.getRight());
return temp;
}
toString |
---|
public String toString()
{
UnorderedListADT<BinaryTreeNode> nodes =
new ArrayUnorderedList<BinaryTreeNode>();
UnorderedListADT<Integer> levelList =
new ArrayUnorderedList<Integer>();
BinaryTreeNode current;
String result = "";
int printDepth = this.getHeight();
int possibleNodes = (int)Math.pow(2, printDepth + 1);
int countNodes = 0;
nodes.addToRear(root);
Integer currentLevel = 0;
Integer previousLevel = -1;
levelList.addToRear(currentLevel);
while (countNodes < possibleNodes)
{
countNodes = countNodes + 1;
current = nodes.removeFirst();
currentLevel = levelList.removeFirst();
if (currentLevel > previousLevel)
{
result = result + "\n\n";
previousLevel = currentLevel;
for (int j = 0; j < ((Math.pow(2, (printDepth - currentLevel))) - 1); j++)
result = result + " ";
}
else
{
for (int i = 0; i < ((Math.pow(2, (printDepth - currentLevel + 1)) - 1)) ; i++)
{
result = result + " ";
}
}
if (current != null)
{
result = result + (current.getElement()).toString();
nodes.addToRear(current.getLeft());
levelList.addToRear(currentLevel + 1);
nodes.addToRear(current.getRight());
levelList.addToRear(currentLevel + 1);
}
else {
nodes.addToRear(null);
levelList.addToRear(currentLevel + 1);
nodes.addToRear(null);
levelList.addToRear(currentLevel + 1);
result = result + " ";
}
}
return result;
}
preorder |
---|
public Iterator<T> iteratorPreOrder()
{
ArrayUnorderedList<T> tempList = new ArrayUnorderedList<T>();
preOrder(root, tempList);
return new TreeIterator(tempList.iterator());
}
protected void preOrder(BinaryTreeNode<T> node,
ArrayUnorderedList<T> tempList)
{
if(node!=null)
{
System.out.print(node.getElement()+" ");
tempList.addToRear(node.getElement());
preOrder(node.getLeft(),tempList);
preOrder(node.getRight(),tempList);
}
}
实验有点难,借鉴了书上和网上的一部分代码。。。还需努力
标签:遍历 unit info htm mic 使用 中缀 日期 null
原文地址:https://www.cnblogs.com/Stark-GR/p/11874363.html