弄了一天终于搞定了,各种问题不断。不管怎么说,还是解决了 :)
我就不多说了,这个博客是写给我自己看的。下次写一个更加完整的,更加完美的二叉树出来在更新此次的代码!
package DataStructure.Structure.Tree;
import java.util.concurrent.LinkedBlockingQueue;
class Node {
Node left;
Node right;
int data;
public Node(int data) {
this.data = data;
}
}
public class Tree {
Node root;
public Tree(int k) {
root = new Node(k);
root.left = null;
root.right = null;
}
public void insert(int data) {
Node point = root;
judge(data,point);
}
public void judge(int data,Node point) {
if (data < point.data) { //如果比根节点小挂在树根root的左边
if (point.left == null) { //如果根节点的左边不为空,则继续向左边递归
point.left = new Node(data);
} else {
judge(data,point.left);
}
}
if (data > point.data) { //如果比根节点大挂在树根root的右边
if (point.right == null) { //如果根节点的右边不为空,则继续向右边递归
point.right = new Node(data);
} else {
judge(data,point.right);
}
}
}
//先序遍历:在递归左儿子之前输出
public void preOrderPrint(Node node) {
if (node != null) {
System.out.print(node.data + " ");
preOrderPrint(node.left);
preOrderPrint(node.right);
}
}
//中序遍历:在递归左儿子之后输出
public void inOrderPrint(Node node) {
if (node != null) {
inOrderPrint(node.left);
System.out.print(node.data + " ");
inOrderPrint(node.right);
}
}
//后序遍历:在递归右儿子之后输出
public void postOrderPrint(Node node) {
if (node != null) {
preOrderPrint(node.left);
preOrderPrint(node.right);
System.out.println(node.data + " ");
}
}
/**
* 层序遍历:
* 1、从队列中取出一个元素入队
* 2、访问该元素对应的结点
* 3、若该结点的左右子结点不为空,则将左右子结点入队
*/
public void levelOrderPrint() {
LinkedBlockingQueue<Node> queue = new LinkedBlockingQueue<>(); //创建一个队列
queue.offer(root);
while (!queue.isEmpty()) {
if (queue.peek().left != null) {
queue.offer(queue.peek().left);
}
if (queue.peek().right != null) {
queue.offer(queue.peek().right);
}
System.out.print(queue.poll().data + " ");
}
}
}
破例使用了一次jdk自带的队列,哈哈真香!(前段时间为了展示自己会写队列和栈每次都自己写一个,亲自体验了一下。还是别人的东西好用!>_< )
怎么说呢,弄了两天了。理论弄了一天,理解代码用了好久,写代码也用了好久。终于完成了!最大的体验不是说终于会"树"了,而是递归。我只能说,刚开始看代码,一脸懵!这个递归是个什么东西?它在干嘛?把代码搞得一团糟!真正使用的时候,真香,如果用栈来实现遍历要多好多代码。虽然还有几个函数没有实现,但是已经迫不及待的想要告诉大家了!哈哈~~
(允许我矫情两句:如果说之前读书是为了卖弄自己读过两本书的话,那么现在读书真的是身不由己!随便打开一本数据结构的书,基本没有会的 :) 之前偶尔看到的一些散句子"有梦想很好呀!更重要的是与梦想相遇那一刻的情怀)