欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用java写的一个简单二叉树的插入和中序遍历

程序员文章站 2022-03-06 12:52:11
...
树的节点bean
public class TreeNode {
	
	//节点的内容
	private NodeBean  data ;
	//左节点
	private TreeNode left;
	//右节点
	private TreeNode rigth;
	
	//构造函数
	public TreeNode(){
		data = new NodeBean();
	}
}


二叉树类
public class Tree {
	private TreeNode root;
	
	Tree(){
		root = new TreeNode();
		NodeBean nodeBean = new NodeBean();
		nodeBean.setKey(60);
		root.setData(nodeBean);
	}
	
	public NodeBean find(int key){
		return null;
	}
	
	//给树插入数据	
	public void insert(TreeNode root,TreeNode bean) {
		if (root == null) {
			root = bean;
		} else {
			if (bean.getData().getKey() < root.getData().getKey()) {
				if (root.getLeft() == null) {
					root.setLeft(bean);
				} else{
					insert(root.getLeft(),bean);
				}
			} else {
				if (root.getRigth() == null) {
					root.setRigth(bean);
				} else{
					insert(root.getRigth(),bean);
				}
			}
		}
	}
	
	//中序遍历二叉树
	public  String  middleIterator(TreeNode tree){
		StringBuilder sb = new StringBuilder();
		
		if (tree == null) {
			return sb.toString();
		} else{
			sb.append(tree.getData().getKey()+",");
			
			sb.append(middleIterator(tree.getLeft()));
			
			sb.append(middleIterator(tree.getRigth()));
		}
		
		return sb.toString();
	}
	
	
	public static void main(String[] args) {
		Tree myTree = new Tree();
		TreeNode treeNode = new TreeNode();
		treeNode.getData().setKey(50);
		
		TreeNode treeNode1 = new TreeNode();
		treeNode1.getData().setKey(45);
		
		TreeNode treeNode2 = new TreeNode();
		treeNode2.getData().setKey(30);
		
		TreeNode treeNode3 = new TreeNode();
		treeNode3.getData().setKey(55);
		
		TreeNode treeNode4 = new TreeNode();
		treeNode4.getData().setKey(70);
		
		myTree.insert(myTree.root, treeNode);
		myTree.insert(myTree.root, treeNode1);
		myTree.insert(myTree.root, treeNode2);
		myTree.insert(myTree.root, treeNode3);
		myTree.insert(myTree.root, treeNode4);
		
		String result = myTree.middleIterator(myTree.getRoot());
		System.out.println(result);
	}
相关标签: Java Bean