package binarytree;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author Gavenyeah
* @date Time: 2016年4月10日下午10:14:08
* @des:
*/
public class BinaryTree {
Node root = null;// 二叉树的根节点
// 二叉树的节点插入
public void insert(int val) {
Node newNode = new Node(val);
if (root == null) {
root = newNode;
return;
}
Node current = root;
Node parent = null;
while (true) {
parent = current;
if (val < current.data) {
current = current.left;
if (current == null) {
parent.left = newNode;
return;
}
} else if (val > current.data) {
current = current.right;
if (current == null) {
parent.right = newNode;
return;
}
}
}
}
// 利用数组建立(中序)排序二叉树
public void buildTree(int arrays[]) {
for (int i = 0; i < arrays.length; i++) {
insert(arrays[i]);
}
}
// 中序遍历二叉树
public void inOrder(Node head) {
if (head != null) {
inOrder(head.left);
visit(head);
inOrder(head.right);
}
}
public void inOrder() {
this.inOrder(this.root);
}
public void preOrder(Node head) {
if (head != null) {
visit(head);
preOrder(head.left);
preOrder(head.right);
}
}
public void preOrder() {
this.preOrder(this.root);
}
public void postOrder(Node head) {
if (head != null) {
postOrder(head.left);
postOrder(head.right);
visit(head);
}
}
public void postOrder() {
this.postOrder(this.root);
}
//层次遍历二叉树
public void layerOrder(Node head){
if(head==null){
return ;
}
Queue<Node>queue=new LinkedList<Node>();
queue.add(head);
while(queue.size()>0){
head=queue.poll();
visit(head);
if(head.left!=null){
queue.add(head.left);
}
if(head.right!=null){
queue.add(head.right);
}
}
}
public void layerOrder(){
this.layerOrder(this.root);
}
// 层次遍历输出树的高度
public int levelOfTree(Node head) {
int level = 0;// 记录树的层数
int front = 0;// 标记当前取出的节点标号
int rear = 0;// 标记当前存入队列的节点标号
int last = 1;// 记录当前行最后一个节点的编号,初始值为1,即第一层最后一个节点的编号为1
Queue<Node> queue = new LinkedList<Node>();
queue.add(head);
rear++;// 根节点加入队列
while (queue.size()>0) {
head = queue.poll();
front++;
if (head.left != null) {
queue.add(head.left);
rear++;
}
if (head.right != null) {
queue.add(head.right);
rear++;
}
// 取出的节点数到达每层最后一个节点后,改变树的层数,并使last等于下一层最后一个节点
if (front == last) {
level++;
last = rear;
}
}
return level;
}
public int levelOfTree() {
return this.levelOfTree(this.root);
}
public void visit(Node node) {
System.out.print(node.data + "\t");
}
}
class Node {
int data;
Node left;
Node right;
public Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}
Java二叉树(一)--定义及前序、中序、后序、层次遍历及求高度的实现
最新推荐文章于 2022-03-26 10:15:18 发布