二叉树的构建与遍历 Java

本文介绍了一个简单的二叉树类的实现,包括插入节点、构建树和打印树等功能。通过具体的Java代码示例展示了如何使用递归方法进行节点插入,并提供了一个测试类来验证二叉树的正确构建。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果用Google搜索技术类问题,没有比较好的文章,那么用英文,所以这里输入 binary trees就得到了斯坦福大学用c/c++ , Java三种语言解答的这个问题:http://cslibrary.stanford.edu/110/BinaryTrees.html

// BinaryTree.java

packageTree;

publicclassBinaryTree {

// Root node pointer. Will be null for an empty tree.

privateNoderoot;

privatestaticclassNode {

Nodeleft;

Noderight;

intdata;

Node(intnewData) {

left=null;

right=null;

data= newData;

}

}

/**

Createsanemptybinarytree--anullrootpointer.

*/

publicBinaryTree() {

root=null;

}

/**

Insertsthegivendataintothebinarytree.

Usesarecursivehelper.

*/

publicvoidinsert(intdata) {

root= insert(root, data);

}

/**

Recursiveinsert--givenanodepointer,recurdownand

insertthegivendataintothetree.Returnsthenew

nodepointer(thestandardwaytocommunicate

achangedpointerbacktothecaller).

*/

privateNode insert(Node node,intdata) {

if(node==null) {

node =newNode(data);

}

else{

if(data <= node.data) {

node.left= insert(node.left, data);

}

else{

node.right= insert(node.right, data);

}

}

return(node);// in any case, return the new pointer to the caller

}

publicvoidbuildTree(int[] data){

for(inti=0;i<data.length;i++){

insert(data[i]);

}

}

publicvoidprintTree() {

printTree(root);

System.out.println();

}

privatevoidprintTree(Node node) {

if(node ==null)return;

// left, node itself, right

printTree(node.left);

System.out.print(node.data+"");

printTree(node.right);

}

}

测试类代码如下:

//test.java

public class test {

public static void main(String[] args) {

BinaryTree biTree=new BinaryTree();

int[] data={2,8,7,4};

biTree.buildTree(data);

biTree.printTree();

}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值