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

关于二叉树,首先考虑的是二叉树的创建及遍历

参考网上的资料,结合自身的情况,给出二叉树的基本功能的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);
	          }
	      }
	  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值