JAVA 实现二叉树。

一、创建结点类:

package com.test.tree; public class Node { public Node leftNode; public Node rightNode; int data; /** * @author hbliu * @param newData */ public Node(int newData) { this.data = newData; this.leftNode = null; this.rightNode = null; } }

二、创建树类:

package com.test.tree; public class BinaryTree { private Node root; /** * 功 能:创建一个空的二凡树 */ public BinaryTree() { root = null; } /** * @author hbliu * @param data 要插入的数值 * 功 能:将数据data插入到树中 */ public void insert(int data){ this.root = insert(root,data); } /** * * @param node 当前的结点,就是根结点。 * @param data 要插入的数值 * @return * 功 能:将数值插入到二叉树中,比较前结点小或等于当前结点的插在当前结点的左则, * 比当前结点大的数据插在当前结点的右则,每次从根结点开始递归比较 */ private Node insert(Node node ,int data){ if( node == null ){ node = new Node(data); }else if (node.data >= data){ node.leftNode = insert(node.leftNode,data); }else{ node.rightNode = insert(node.rightNode,data); } return node; } /** * @author hbliu * @param data 要插入的数据 * 功 能:构建二叉树 */ private void buildTree(int[] arraydDta){ for (int i = 0; i < arraydDta.length; i++) { insert(arraydDta[i]); } } public void buildTree(){ int arrayData[]={10,3,1,2,4,7,12,15}; buildTree(arrayData); } /** * @author hbliu */ public void printTree(){ printTree(this.root); System.out.println(); } /** *@author hbliu * @param node */ public void printTree(Node node){ if (node == null){ return ; } printTree(node.leftNode); System.out.print(node.data + " "); printTree(node.rightNode); } public static void main(String[] arg){ BinaryTree BT = new BinaryTree(); BT.buildTree(); BT.printTree(); } }

三、要认真的思考递归在树中的运用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值