二叉查找树代码java+运行结果
发布日期:2021-10-12 20:08:26
浏览次数:4
分类:技术文章
本文共 1629 字,大约阅读时间需要 5 分钟。
1.代码
package TestTree;/* * zt * 2020/8/3 * 14:41 *二叉查找树: */public class BinarySortTree { //根节点 private Node root; //元素个数 private int size; public int getSize() { return size; } //添加元素 public void add(int v){ if(root==null){//当前树是空的 root = new Node(v); size++; System.out.println("添加了根元素"+v); }else{//不是空 //给根添加子节点 if(root.addChild(v)){ size++; } } } //中序遍历 public void middleleList(){ root.printNode(); } /* 节点类型 */ static class Node { //元素值 private int item; //左节点 private Node left; //右节点 private Node right; public Node(int item) { this.item = item; } //添加孩子节点方法 public boolean addChild(int v) { if (this.item > v) {//v放在左边 if (this.left == null) {//左边没有元素 this.left = new Node(v); System.out.println(v+"放在"+this.item+"的左边"); } else { return this.left.addChild(v);//递归(可能出现重复元素false的情况) } }else if(this.item
将main方法写在了另一个测试类里面
package TestTree;/* * zt * 2020/8/3 * 15:03 * */public class TestBinarySortTree { public static void main(String[] args) { BinarySortTree tree = new BinarySortTree(); tree.add(10); tree.add(30); tree.add(30); tree.add(40); tree.add(50); System.out.println("元素个数:"+tree.getSize()); tree.middleleList(); }}
2.运行结果
添加了根元素1030放在10的右边30重复元素40放在30的右边50放在40的右边元素个数:410304050
转载地址:https://blog.csdn.net/qq_39773004/article/details/107767947 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
不错!
[***.144.177.141]2024年04月01日 17时40分39秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
想认识比你厉害的人,你应该注意的几个细节
2019-04-25
你辛辛苦苦考的大学,就有资格让你去骚扰女生?
2019-04-25
微信更新,重点关注!
2019-04-25
这个小常识,竟然还有人不知道!
2019-04-25
对降准的一点看法
2019-04-25
你有「玻璃心」吗?
2019-04-25
解惑 | 一个接地气的提问!
2019-04-25
容易被忽略的陌生人社交礼仪!
2019-04-25
DbHelper
2019-04-25
SqlHelper
2019-04-25
ArticleDAL
2019-04-25
git 终端显示中文乱码
2019-04-25
关于java.lang.IllegalStateException: getOutputStream() has already been called for this response求解
2019-04-25
oracle 10.2.0.1.0 误删除数据文件 后的处理方法
2019-04-25
JPA 默认值配置
2019-04-25
myeclipse 的 maven工程报错或pom.xml头报错解决办法
2019-04-25
反向Ajax,第2部分:WebSocket
2019-04-25
反向Ajax,第1部分:Comet介绍
2019-04-25
反向Ajax,第3部分:Web服务器和Socket.IO
2019-04-25
反向Ajax,第4部分:Atmosphere和CometD
2019-04-25