数据结构——简单表达式二叉树实现

数据结构——简单表达式二叉树实现

今天我们来了解——树这种结构

树由根节点出发有若干个节点,每个节点又有若干个子节点,这样由上而下构成一个类似树根的结构

其中最具有代表性的莫过于二叉树了

今天我们来实现一个最简单的表达式二叉树

比如:4+23*56/2-0

我们先需要一个Node节点类

具有左右两个子节点属性,还有一个数据域

public class Node {
	private Node left;
	private Node right;
	private String data;
	
	public Node(String data){
		this.data=data;
	}
	public Node(String data,Node left,Node right){
		this.data=data;
		this.left=left;
		this.right=right;
	}
}

两个构造方法分别用来创建父节点和普通节点

然后分别设置属性的set,get方法即可

然后我们根据表达式来写一个二叉树类

public class BinaryTree {

	private Node root;//声明根节点
	private String s="";
}

声明两个属性一个是根节点属性,还有一个String属性

然后我们声明两个数组队列分别用来存储操作符和数值

使用一个for循环遍历字符串,然后将数值和操作符分别存储

public BinaryTree(String str){
		//存放操作符的数组队列
		ArrayList<String> oper=new ArrayList<String>();
		//存放节点数据的数组队列
		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));
				s="";
				oper.add(ch+"");
			}
		}
		//把最后的数字加入到数字节点中
		numList.add(new Node(s));
}

然后我们每次取出两个数值和一个操作符用来构建节点

while(oper.size()>0){
			//取出存储的数
			Node left=numList.remove(0);
			Node right=numList.remove(0);
			String ope=oper.remove(0);
			
			Node node=new Node(ope, left, right);
			numList.add(0, node);
		}
		//最后让根节点等于第一个节点
		root=numList.get(0);

这样一个简单的表达式二叉树就建立好了,最后我们写一个方法来测试一下吧

利用递归得到中序遍历的二叉树

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 void output(){
		output(root);
}

最后将方法封装方便我们使用时调用!

猜你喜欢

转载自blog.csdn.net/qq_41819698/article/details/82430722