二叉树基础操作 ,前中后序遍历,求二叉树高度,二叉搜索树(二叉排序树)Java实现 代码集合

首先,定义一个树类Tree.java

public class Tree {
   
	public TreeNode root;
}

定义树节点类TreeNode.java

public class TreeNode {
   
	
	public TreeNode(int data) {
   
		this.data = data;
	}
	public int data;
	public TreeNode left;
	public TreeNode right;
	public void showData(){
   
		System.out.println(data);//节点访问操作
	}
}

二叉树的基本操作类 TreeUtils.java,
实现了增加树节点,删除树节点,搜索节点
生成二叉搜索树(左子树总小于右子树,中序遍历有序)

public class TreeUtils {
   
	public static void addNode(Tree t,TreeNode node){
   //将一个节点增加到已有二叉树(节点按二叉搜索树规则增加)
		if(t.root==null){
   
			t.root = node;
		}else{
   
			TreeNode current = t.root;//开始
			while(true){
   
				if(node.data<current.data){
   
					if(current.left==null){
   
						current.left = node;
						return;
					}else{
   
						current = current.left;
						continue;
					}
				}else{
   
					if(current.right==null){
   
						current.right = node;
						return;
					}else{
   
						current = current.right;
						continue;
					}
				}
			}
		}
	}
	
	public static void preOrderRecursive(TreeNode node){
   //前序遍历
		if(node
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值