博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
二叉树
阅读量:4329 次
发布时间:2019-06-06

本文共 1564 字,大约阅读时间需要 5 分钟。

/**

* 二叉树优点:1.有序数组;2.链表。
* 数值大的在放右边,小的放左边
*
*/

public class TreeList {

public static void main(String[] args){
TreeList tl = new TreeList();
tl.insertNode(1);
tl.insertNode(21);
tl.insertNode(23);
tl.insertNode(14);
tl.insertNode(5);
tl.insertNode(46);
tl.insertNode(27);
tl.insertNode(18);
tl.insertNode(79);
tl.insertNode(10);
tl.inorderTraversal();
}
TreeNode root;
//插入结点
public synchronized void insertNode(int insertValue){
if(root == null){
root = new TreeNode(insertValue);
} else{
root.insert(insertValue);
}
}
//前序遍历
public synchronized void preorderTraversal(){
preorderHepler(root);
}
private void preorderHepler(TreeNode node){
if(node==null){
return;
}
System.out.println(node.data+" ");
preorderHepler(node.leftNode);
preorderHepler(node.rightNode);
}
//中序遍历 值从小到大显示
public synchronized void inorderTraversal(){
inorderHepler(root);
}
private void inorderHepler(TreeNode node){
if(node==null){
return;
}
inorderHepler(node.leftNode);
System.out.println(node.data+" ");
inorderHepler(node.rightNode);
}
}
class TreeNode{
TreeNode leftNode;
TreeNode rightNode;
int data;
public TreeNode(){
super();
}
public TreeNode(int nodeData){
this.data = nodeData;
this.leftNode = this.rightNode = null;
}
public synchronized void insert(int insertValue){
if(insertValue<data){
if(leftNode==null){
leftNode = new TreeNode(insertValue);
}else{
leftNode.insert(insertValue);
}
} else if (insertValue>data){
if(rightNode==null){
rightNode = new TreeNode(insertValue);
}else{
rightNode.insert(insertValue);
}
}
}
}

转载于:https://www.cnblogs.com/huangyin/p/5970013.html

你可能感兴趣的文章
百度移动搜索主要有如下几类结果构成
查看>>
Python爬虫面试题170道:2019版【1】
查看>>
JavaBean规范
查看>>
第四阶段 15_Linux tomcat安装与配置
查看>>
NAS 创建大文件
查看>>
学习笔记-模块之xml文件处理
查看>>
接口测试用例
查看>>
面试:用 Java 实现一个 Singleton 模式
查看>>
Sybase IQ导出文件的几种方式
查看>>
案例:手动输入一个字符串,打散放进一个列表,小写字母反序 大写字母保持不变...
查看>>
linux 系统下 tar 的压缩与解压缩命令
查看>>
阿里负载均衡,配置中间证书问题(在starcom申请免费DV ssl)
查看>>
转:How to force a wordbreaker to be used in Sharepoint Search
查看>>
MySQL存储过程定时任务
查看>>
Python中and(逻辑与)计算法则
查看>>
POJ 3267 The Cow Lexicon(动态规划)
查看>>
设计原理+设计模式
查看>>
音视频处理
查看>>
tomcat 7服务器跨域问题解决
查看>>
前台实现ajax 需注意的地方
查看>>