java 二叉树

2021-07-03 20:04

阅读:536

标签:判断   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=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


评论


亲,登录后才可以留言!