表达二叉树的特点:运算符作为父节点,运算的数字分别为左右子节点
第一步:遍历公式,找出所有的运算符和 数字,分别构建节点存储
第二步:从运算符列表中去除第一个运算符,取出两个运算的数字,构建一个节点,并且放回数字列表中
第三步:重复第二步,直到数字列表只剩一个节点,该节点就是根节点
节点的属性:左右子节点,数据
节点类的代码:
public class Node {
private Object data;//数据
private Node left;//左节点
private Node right;//右节点
public Node(){
}
public Node(Object data) {
super();
this.data = data;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
}
表达二叉树类:
public class TwoTree<E> {
private Node root;//根节点
private String s = "";
public void add(String str) {
// 声明一个数组列表,存放操作符,加减乘除
ArrayList<Node> operList = new ArrayList<Node>();
// 声明一个数组列表,存放节点的数据
ArrayList<Node> numList = new ArrayList<Node>();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);// 取出字符串的各个字符
if (ch >= '0' && ch <= '9') {//如果是数字
s += ch;
} else {//如果是运算符
numList.add(new Node(s));//将数字添加到numList中
s = "";
operList.add(new Node(ch));//将符号添加到operList中
}
}
// 把最后一个数字加入numList
numList.add(new Node(s));
while (operList.size() > 0) {
Node left = numList.remove(0);//取出数字numList中的第一位(并且移除)
Node right = numList.remove(0);//取出数字numList中的第一位(并且移除)
Node oper = operList.remove(0);//取出字符operList中的第一位(并且移除)
oper.setLeft(left);//将运算符作为父节点,将取出的两个节点分别作为左,右子节点
oper.setRight(right);
numList.add(0, oper);// 将新生的节点作为第一个节点
}
// 让根节点等于最后一个节点
root = numList.get(0);
}
public void output() {
output(root);
}
/**
* 递归 中序遍历
*/
public void output(Node node) {
if (node.getLeft() != null) {
output(node.getLeft());
}
System.out.print(node.getData());
if (node.getRight() != null) {
output(node.getRight());
}
}
}
用来测试的类:
public class Manage {
public static void main(String[] args) {
TwoTree tt = new TwoTree();
tt.add("9+8-5+2-4+2");
tt.output();
}
}
输出结果: 9+8-5+2-4+2
---------------------
【转载,仅作分享,侵删】
作者:lzq1326253299
原文:https://blog.csdn.net/lzq1326253299/article/details/82222445
版权声明:本文为博主原创文章,转载请附上博文链接!
|
|