java实现二叉树

用java实现实现二叉树

第一步:创建节点类

<span style="font-size:18px;">class TreeNode {
	private Object nodeValue;
	private TreeNode left, right;
	
	public TreeNode(){
		this(null, null, null);
	}
	
	public TreeNode(Object item){
		nodeValue = item;
	}
	
	public TreeNode(Object item, TreeNode left, TreeNode right){
		nodeValue = item;
		this.left = left;
		this.right = right;
	}
	//判断当前节点是否为叶子
	public boolean isEmpty(){
		if (this.left == null && this.left == null){
			return true;
		}
		return false;
	}
	//重写toString方法
	public String toString(){
		if (nodeValue == null){
			return null;
		}
		
		String result = "(节点" + nodeValue.toString();
		
		if (left != null){
			result += "左节点" + left.toString();
		}
		if (right != null){
			result += "右节点" + right.toString();
		}
		
		result += ")";
		return result;
	}
}

//实现二叉树
class BinaryTree {
    protected TreeNode root;//定义一个节点对象成员
    
    public BinaryTree(){
        root = null;
    }
    
    public BinaryTree(TreeNode root){
        this.root = root;
    }
    
    public boolean isEmpty(){
        return this.root == null;
    }
    
    public TreeNode getRoot(){
        return root;
    }
    
    public String toString(){
        return root.toString();
    }
}


实现如图所示的二叉树
<img src="https://img-blog.csdn.net/20160418211703770?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" height="259" width="572" />
</span>

//构造二叉树

<span style="font-size:18px;">public class BulidBinaryTree {
	public static BinaryTree creat(){
		TreeNode a, b, c, d, e, f, g;
		//创建叶子
		f = new TreeNode("F");
		g = new TreeNode("G");
		d = new TreeNode("D");
		c = new TreeNode("C");
		//创建根节点
		e = new TreeNode("E", f, g);
		b = new TreeNode("B", d, e);
		a = new TreeNode("A", b, c);
		
		return new BinaryTree(a);
	} 
}
</span>

//测试并输出

<span style="font-size:18px;">public class TestDemo {
	public static void main(String[] args) {
		BinaryTree binaryTree = BulidBinaryTree.creat();
		System.out.println(binaryTree);
	}
}
结果如下
</span>



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值