二叉排序树的建立和先序遍历和层次遍历问题之java实现

本文介绍了一种使用Java实现二叉搜索树的方法,包括插入节点、中序遍历和层次遍历等功能。通过具体实例展示了如何创建二叉树并进行基本的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.*;


class Node
{
int key;
Node left;
Node right;
Node(int key)
{
this.key = key;
left = null;
right = null;
}
}


class Tree
{  
void insert(Node root,int k)
{
int value = root.key;
Node node = new Node(k);
if(k < value)
{
if(root.left == null)
    {
   root.left = node;
    }
   else
{
       insert(root.left,k);
}
}
else if(k > value)
{
if(root.right == null)
   root.right = node;
else
   insert(root.right,k);
}
}
void mid(Node root)
{
if(root == null)
return;
else
{
mid(root.left);                                          //中序遍历
System.out.print(root.key + " ");
mid(root.right);
}
}
void level(Node root)                                       //层次遍历,注意用到了LinkedList,用来存储相关的节点,模拟一个队列的方式。
{
if(root == null)
return;
List<Node> queue = new LinkedList<Node>();
queue.add(root);
while(!(queue.isEmpty()))
{
Node temp = queue.remove(0);                                             //用队列的方式来实现层次遍历,先进先出
System.out.print(temp.key + " ");
if(temp.left != null)
queue.add(temp.left);
if(temp.right != null)
queue.add(temp.right);
}
System.out.println();
}
}


public class Test
{
public static void main(String args[])
{
int array[] = {19,12,4,5,7};
Node root = new Node(array[0]);
Tree tree = new Tree();
for(int i = 0; i < array.length; i++)
{
tree.insert(root, array[i]);
}
tree.mid(root);
System.out.println();
tree.level(root);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值