❶ 用java怎么构造一个二叉树
定义一个结点类:
public class Node {
private int value;
private Node leftNode;
private Node rightNode;
public Node getRightNode() {
return rightNode;
}
public void setRightNode(Node rightNode) {
this.rightNode = rightNode;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getLeftNode() {
return leftNode;
}
public void setLeftNode(Node leftNode) {
this.leftNode = leftNode;
}
}
初始化结点树:
public void initNodeTree()
{
int nodeNumber;
HashMap<String, Integer> map = new HashMap<String, Integer>();
Node nodeTree = new Node();
Scanner reader = new Scanner(System.in);
nodeNumber = reader.nextInt();
for(int i = 0; i < nodeNumber; i++) {
int value = reader.nextInt();
String str = reader.next();
map.put(str, value);
}
if (map.containsKey("#")) {
int value = map.get("#");
nodeTree.setValue(value);
setChildNode(map, value, nodeTree);
}
preTraversal(nodeTree);
}
private void setChildNode(HashMap<String, Integer> map, int nodeValue, Node parentNode) {
int value = 0;
if (map.containsKey("L" + nodeValue)) {
value = map.get("L" + nodeValue);
Node leftNode = new Node();
leftNode.setValue(value);
parentNode.setLeftNode(leftNode);
setChildNode(map, value, leftNode);
}
if (map.containsKey("R" + nodeValue)) {
value = map.get("R" + nodeValue);
Node rightNode = new Node();
rightNode.setValue(value);
parentNode.setRightNode(rightNode);
setChildNode(map, value, rightNode);
}
}
前序遍历该结点树:
public void preTraversal(Node nodeTree) {
if (nodeTree != null) {
System.out.print(nodeTree.getValue() + "\t");
preTraversal(nodeTree.getLeftNode());
preTraversal(nodeTree.getRightNode());
}
}
❷ 写一个java层次遍历二叉树,简单点就可以,我要的是代码,不是纯文字说明
public class BinaryNode {
Object element;
BinaryNode left;
BinaryNode right;
}
import java.util.*;
public class Queue {
protected LinkedList list;
// Postcondition: this Queue object has been initialized.
public Queue() {
list = new LinkedList();
} // default constructor
// Postcondition: the number of elements in this Queue object has been
// returned.
public int size() {
return list.size();
} // method size
// Postcondition: true has been returned if this Queue object has no
// elements. Otherwise, false has been returned.
public boolean isEmpty() {
return list.isEmpty();
} // method isEmpty
// Postconditon: A of element has been inserted at the back of this
// Queue object. The averageTime (n) is constant and
// worstTime (n) is O (n).
public void enqueue(Object element) {
list.addLast(element);
} // method enqueue
// Precondition: this Queue object is not empty. Otherwise,
// NoSuchElementException will be thrown.
// Postcondition: The element that was at the front of this Queue object -
// just before this method was called -- has been removed
// from this Queue object and returned.
public Object dequeue() {
return list.removeFirst();
} // method dequeue
// Precondition: this Queue object is not empty. Otherwise,
// NoSuchElementException will be thrown.
// Postcondition: the element at index 0 in this Queue object has been
// returned.
public Object front() {
return list.getFirst();
} // method front
} // Queue class
import java.io.IOException;
public class BinaryTree {
BinaryNode root;
public BinaryTree() {
super();
// TODO 自动生成构造函数存根
root=this.createPre();
}
public BinaryNode createPre()
//按照先序遍历的输入方法,建立二叉树
{
BinaryNode t=null;
char ch;
try {
ch = (char)System.in.read();
if(ch==' ')
t=null;
else
{
t=new BinaryNode();
t.element=(Object)ch;
t.left=createPre();
t.right=createPre();
}
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
return t;
}
public void inOrder()
{
this.inOrder(root);
}
public void inOrder(BinaryNode t)
//中序遍历二叉树
{
if(t!=null)
{
inOrder(t.left);
System.out.print(t.element);
inOrder(t.right);
}
}
public void postOrder()
{
this.postOrder(root);
}
public void postOrder(BinaryNode t)
//后序遍历二叉树
{
if(t!=null)
{
postOrder(t.left);
System.out.print(t.element);
postOrder(t.right);
}
}
public void preOrder()
{
this.preOrder(root);
}
public void preOrder(BinaryNode t)
//前序遍历二叉树
{
if(t!=null)
{
System.out.print(t.element);
preOrder(t.left);
preOrder(t.right);
}
}
public void breadthFirst()
{
Queue treeQueue=new Queue();
BinaryNode p;
if(root!=null)
treeQueue.enqueue(root);
while(!treeQueue.isEmpty())
{
System.out.print(((BinaryNode)(treeQueue.front())).element);
p=(BinaryNode)treeQueue.dequeue();
if(p.left!=null)
treeQueue.enqueue(p.left);
if(p.right!=null)
treeQueue.enqueue(p.right);
}
}
}
public class BinaryTreeTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
BinaryTree tree = new BinaryTree();
System.out.println("先序遍历:");
tree.preOrder();
System.out.println();
System.out.println("中序遍历:");
tree.inOrder();
System.out.println();
System.out.println("后序遍历:");
tree.postOrder();
System.out.println();
System.out.println("层次遍历:");
tree.breadthFirst();
System.out.println();
}
}
❸ java中queue的使用方法
java中的queue类是队列数据结构管理类。在它里边的元素可以按照添加它们的相慧握同顺序被移除。
队列通常(但并非一定)以 FIFO(先进先出)的方式排序各个元素。不过优先级队列和 LIFO 队列(或堆栈)例外,前者根据提供的比较器或元素的自然顺序对元素进行排序,后者稿岁按 LIFO(后进先出)的方式对元素进行排序。无论使用哪种排序方式,队列的头都是调用remove()或poll()所移除的元素。在 FIFO 队列中,所有的新元素都插入队列的末尾。其他种类的队列可能使用不同的元素放置规则。每个Queue实现必须指定其顺序属性。
offer 添加一个元素并返回true 如果队列已满,则返回false
poll 移除并返问队列头部的元素 如果队列为空,则返回null
peek 返回队列头部前敬庆的元素 如果队列为空,则返回null
put 添加一个元素 如果队列满,则阻塞
take 移除并返回队列头部的元素 如果队列为空,则阻塞
element 返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
add 增加一个元索 如果队列已满,则抛出一个IIIegaISlabEepeplian异常
remove 移除并返回队列头部的元素 如果队列为空,则抛出一个
NoSuchElementException异常
注意:poll和peek方法出错进返回null。因此,向队列中插入null值是不合法的。
还有带超时的offer和poll方法重载,例如,下面的调用:
boolean success = q.offer(x,100,TimeUnit.MILLISECONDS);
尝试在100毫秒内向队列尾部插入一个元素。如果成功,立即返回true;否则,当到达超时进,返回false。同样地,调用:
Object head = q.poll(100, TimeUnit.MILLISECONDS);
如果在100毫秒内成功地移除了队列头元素,则立即返回头元素;否则在到达超时时,返回null。
阻塞操作有put和take。put方法在队列满时阻塞,take方法在队列空时阻塞。
Queue接口与List、Set同一级别,都是继承了Collection接口。LinkedList实现了Queue接 口。Queue接口窄化了对LinkedList的方法的访问权限(即在方法中的参数类型如果是Queue时,就完全只能访问Queue接口所定义的方法 了,而不能直接访问 LinkedList的非Queue的方法),以使得只有恰当的方法才可以使用。BlockingQueue 继承了Queue接口。
❹ 求java多线程遍历目录的完整代码,能运行的那种
目录结构为树型结构,用多线程不大好做,线程最多在前几层进行分割,比如每个目录下有两个目录,共5层,那么root目录下就能启用2个线程分别进行遍历,所以第二层就启动了2个线程进行遍历,加上主线程共三个线程,虽然这样做是可以做,但是要更具实际情况进行线程的规划,否则容易线程过多导致cpu超负荷,或者假死,再提一点,遍历目录不建议用递归来写,因为目录较多容易栈溢出。
随手写了个,会有点bug就是关闭线程池的时候,还有就是有可能目录太多进入拒绝策略,这个东西 可以考虑使用令牌桶算法,或者计数器算法来做。这里提供个简单的例子。
public class TraverseUtil {
public static BlockingQueue blockingQueue = new LinkedBlockingQueue(100);
public static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(100,100,10, TimeUnit.SECONDS,blockingQueue);
public static void traverseFolder2(String path) {
File file = new File(path);
if (file.exists()) {
File[] files = file.listFiles();
if (null == files || files.length == 0) {
System.out.println("文件夹是空的!");
return;
} else {
for (File file2 : files) {
if (file2.isDirectory()) {
System.out.println("文件夹:" + file2.getAbsolutePath());
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
traverseFolder2(file2.getAbsolutePath());
}
});
} else {
System.out.println("文件:" + file2.getAbsolutePath());
}
}
}
} else {
System.out.println("文件不存在!");
}
}
public static void main(String[] args) throws InterruptedException {
traverseFolder2("C:\\Users\\a8932\\Desktop\\md");
}
}
❺ 用java实现循环队列
简单写了下,希望你能看明白
import java.util.ArrayList;
public class SeqQueue {
ArrayList<String> list;
public SeqQueue() {
list = new ArrayList<String>();
}
public String getFirst() {
if (!list.isEmpty()) {
String s = list.get(0);
list.remove(0);
return s;
}
return null;
}
public void insertLast(String s) {
list.add(s);
}
public static void main(String[] args) {
SeqQueue seq = new SeqQueue();
seq.insertLast("111");
seq.insertLast("222");
seq.insertLast("333");
System.out.println(seq.getFirst());
System.out.println(seq.getFirst());
System.out.println(seq.getFirst());
}
}
❻ Java如何使用数组实现循环队列的案例
class Element{
int id;
String name;
Element(int a,String n){
id=a;name=n;
}
}
class SeqQueue{
int first,last,maxsize;
Element queue[];
SeqQueue(int i){
maxsize=i;
first=last=-1;
queue=new Element[i];
}
public void clear(){//置空
first=last=-1;
}
public boolean isEmpty(){//判空
if(first==-1)return true;
else return false;
}
public Element getFirst(){//取队列头元素
if(first==-1)return null;
else return queue[first+1];
}
public boolean isFull(){//判满
if((last+1)%maxsize==first)return true;
else return false;
}
public boolean enQueue(Element e){//入队
if(this.isFull())return false;
if(this.isEmpty())
first=last=0;
else
last=(last+1)%maxsize;
queue[last]=e;
return true;
}
public Element deQueue(){//出队
Element t=queue[first];
if(this.isEmpty())return null;
if(first==last){
queue[first]=null;
this.clear();
return t;
}
queue[first]=null;
first=(first+1)%maxsize;
return t;
}
public int getLength(){//队列长度
if(last>=first)return last-first+1;
else return maxsize-(first-last)+1;
}
public void display(){//打印所有元素
int i,j;
for (i=first,j=0;j<this.getLength();i=(i+1)%maxsize,j++)
System.out.println(queue[i].id);
}
}