import java.util.ArrayList;
import java.util.List;
class BSTNode{
private int value=0;
private BSTNode lchild=null;
private BSTNode rchild=null;
public BSTNode() {
}
public BSTNode(int value) {
this.value=value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public BSTNode getLchild() {
return lchild;
}
public void setLchild(BSTNode lchild) {
this.lchild = lchild;
}
public BSTNode getRchild() {
return rchild;
}
public void setRchild(BSTNode rchild) {
this.rchild = rchild;
}
}
public class binary {
public static void insertBSTNode(BSTNode t,BSTNode root)
{
BSTNode next;
next=root;
/*while(true)
{
if(next.getLchild()!=null)
{
if(t.getValue()<next.getValue())
next=next.getLchild();
else if(next.getRchild()!=null)
next=next.getRchild();
else
{
next.setRchild(t);
break;
}
}
else
{
next.setLchild(t);
break;
}
}*/
while(next!=null)
{
if(t.getValue()<next.getValue())
{
if(next.getLchild()!=null)
{
next=next.getLchild();
}
else
{
next.setLchild(t);
return;
}
}
else if(t.getValue()>next.getValue())
{
if(next.getRchild()!=null)
{
next=next.getRchild();
}
else
{
next.setRchild(t);
return;
}
}
else{
throw new RuntimeException("插入节点值已经存在");
}
}
return ;
}
public static void queryBSTNodeByPre(BSTNode bstNode){
if(bstNode !=null){
System.out.println("值:"+bstNode.getValue());
queryBSTNodeByPre(bstNode.getLchild());
queryBSTNodeByPre(bstNode.getRchild());
}else{
return;
}
}
public static void queryBSTNodeByOrder(BSTNode bstNode) {
if(bstNode !=null){
queryBSTNodeByOrder(bstNode.getLchild());
System.out.println("值:"+bstNode.getValue());
queryBSTNodeByOrder(bstNode.getRchild());
}else{
return;
}
}
public static void queryBSTNodeBypost(BSTNode bstNode) {
if(bstNode !=null){
queryBSTNodeBypost(bstNode.getLchild());
queryBSTNodeBypost(bstNode.getRchild());
System.out.println("值:"+bstNode.getValue());
}else{
return;
}
}
//树的深度等于左子树深度或者右子树深度的最小值+1
//使用递归进行遍历
public static int queryBSTNodelength(BSTNode bstNode) {
int l;
int r;
if(bstNode !=null){
l=queryBSTNodelength(bstNode.getLchild());
r=queryBSTNodelength(bstNode.getRchild());
return Math.max(l+1, r+1);
}else{
return 0;
}
}
public static void main(String []args)
{
int[]arr= {8,1,6,7,9,2,5,3};
//使用链表进行存储 ArrayList 是list的子类,所有定义成如下的父类句柄指向子类对象
List <BSTNode>list =new ArrayList <BSTNode> ();
int i;
for(i=0;i<arr.length;i++)
{
//使用add方法将节点加入list数组列表方法里的对象需要new (new BSTNode(arr[i]));
list.add(new BSTNode(arr[i]));
}
// 赋值时需要使用list对象到的get(序号)的方法
BSTNode root=list.get(0);
for(i=1;i<arr.length;i++)
{
insertBSTNode(list.get(i),root);
}
System.out.println("前序遍历:");
queryBSTNodeByPre(root);
System.out.println();
System.out.println("中序遍历:");
queryBSTNodeByOrder(root);
System.out.println();
System.out.println("后序遍历:");
queryBSTNodeBypost(root);
System.out.println();
queryBSTNodelength(root);
System.out.println("长度:"+queryBSTNodelength(root));
}
}
二叉树前序中序后序搜索程序Java
最新推荐文章于 2024-05-06 11:23:19 发布