您的位置:首页 > 编程语言 > Java开发

二叉树的创建及遍历--java实现

2016-10-11 19:36 495 查看
关于二叉树,首先考虑的是二叉树的创建及遍历

参考网上的资料,结合自身的情况,给出二叉树的基本功能的java实现。

源码如下:

//参考:http://www.linuxidc.com/Linux/2013-11/93170.htm
import java.util.LinkedList;
class Node{
int val = 0;
Node leftChild;
Node rightChild;
Node(int x) {
val = x;
}
}
public class binaryTree {
private static Node root  = null;
private static int count = 0;
public static void main(String[] args) {
int[] vals ={1,2,4,0,0,5,0,0,3,0,0};
root = createBinaryTree(vals);
preTraverseTree(root);
System.out.println();
midTraverseTree(root);
System.out.println();
levelTraverse(root);
}
// 使用先序创建一个二叉树
public static Node createBinaryTree(int[] values) {
Node root = null;
if (count >= values.length || values[count++]==0) {
root = null;
} else {
root = new Node(values[count - 1]);
root.leftChild = createBinaryTree(values);
root.rightChild = createBinaryTree(values);
}
return root;
}
// 使用先序遍历一个二叉树
public static void preTraverseTree(Node root) {
if (root == null) {
System.out.print(0);
}else{
System.out.print(root.val);
preTraverseTree(root.leftChild);
preTraverseTree(root.rightChild);
}
}
// 使用中序遍历一个二叉树
public static void midTraverseTree(Node root) {
if (root == null) {
System.out.print(0);
}else{
midTraverseTree(root.leftChild);
System.out.print(root.val);
midTraverseTree(root.rightChild);
}
}
// 层次遍历一棵二叉树
public static void levelTraverse(Node root)
{
if(root == null){
return ;
}
LinkedList<Node> queue = new LinkedList<Node>();
Node current = null;
queue.offer(root);//将根节点入队
while(!queue.isEmpty()){
current = queue.poll();//出队队头元素并访问
System.out.print(current.val +"-->");
if(current.leftChild != null){//如果当前节点的左节点不为空入队
queue.offer(current.leftChild);
}
if(current.rightChild != null){//如果当前节点的右节点不为空,把右节点入队
queue.offer(current.rightChild);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: