java 二叉树
2021-07-03 20:04
标签:判断 htc 查找二叉树 数据 stat private inno dmi tree package com.qifengle.tree; public class Tree { public Tree(int number){ package com.qifengle.tree; public class TreeTest { public TreeTest(){ //查找二叉树的最小值 public static void main(String[] args){ java 二叉树 标签:判断 htc 查找二叉树 数据 stat private inno dmi tree 原文地址:https://www.cnblogs.com/Reqifengle/p/9619686.html
int number;
Tree leftChild;
Tree rightChild;
this.number=number;
}
}
//二叉树根节点
private Tree root;
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
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);
}
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);
}
}