码迷,mamicode.com
首页 > 编程语言 > 详细

java 二叉树

时间:2018-09-10 15:41:25      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:判断   htc   查找二叉树   数据   stat   private   inno   dmi   tree   

package com.qifengle.tree;

public class Tree {
int number;
Tree leftChild;
Tree rightChild;

public Tree(int number){
this.number=number;
}
}

 

 

package com.qifengle.tree;

public class TreeTest {
//二叉树根节点
private Tree root;

public TreeTest(){
root=null;
}
//添加节点
public void addTree(int num){
//1.创建新的节点
Tree newTree=new Tree(num);
//2.判断根节点是否为空
if(root==null){
root=newTree;
}else{
//3.创建两个新的节点,分别表示所要插入节点的父节点和新节点的位置
Tree parentTree=null;
Tree current=root;
while(current!=null){//位置为空才能添加
parentTree=current;
if(num<current.number){//插入数据小,则插入位置变为左节点
current=current.leftChild;
if(current==null){//左节点为空,则插入成
parentTree.leftChild=newTree;
}
}
else{
current=current.rightChild;
if(current==null){
parentTree.rightChild=newTree;
}
}
}
}
}
//遍历二叉树
public void display(Tree current){
if(current!=null){
display(current.leftChild);
System.out.println(current.number);
display(current.rightChild);
}
}
//查找二叉树的最大值
public void findMax(Tree current){
Tree maxNode=null;
if(current==null)
System.out.println("the tree is null");
else{
while(current!=null){
maxNode=current;
current=current.rightChild;
}
}
System.out.println(maxNode.number);
}

//查找二叉树的最小值
public void findMin(Tree current){
Tree minNode=null;
if(current==null)
System.out.println("the tree is null");
else{
while(current!=null){
minNode=current;
current=current.leftChild;
}
}
System.out.println(minNode.number);
}

public static void main(String[] args){
TreeTest test=new TreeTest();
test.addTree(1);
test.addTree(4);
test.addTree(3);
test.display(test.root);
test.findMax(test.root);
test.findMin(test.root);
}
}

java 二叉树

标签:判断   htc   查找二叉树   数据   stat   private   inno   dmi   tree   

原文地址:https://www.cnblogs.com/Reqifengle/p/9619686.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!