java 二叉树的实现与先序遍历和层次遍历

最近在看数据结构的知识,看到好多代码都是用c写的,就想试试用java实现,这里是二叉树的实现和层次遍历和先序遍历,因为中序和后序算法和先序类似,在这里就不写了,亲测可用。
package testfile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;

class Node {  
    String value;  
    Node left;  
    Node right;  
    
    public Node(String s){
    	this.value=s;
    }
}  
public class JavaTree {
	public static Node createTree() throws Exception{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String s=br.readLine();
		Node n ;
		
		
		if(s.equals("#"))
			n=null;
		else{
			n=new Node(s);
			n.left=createTree();
			n.right=createTree();
		}
		
		return n;
	}
	
	
	
	
	public static void breadthTravel(Node n){
		Queue<Node> q=new LinkedList<Node> ();
		if(n==null)
			System.out.println("no data to read");
		else{
			q.offer(n);
			while(!q.isEmpty()){
				Node n1=q.poll();
				System.out.println(n1.value);
				if(n1.left!=null)
					q.offer(n1.left);
				if(n1.right!=null){
					q.offer(n1.right);
				}
			}
		}
	}
	
	public static void PreOrder(Node n){
		if(n==null)
			return;
		else{
			System.out.println(n.value);
			PreOrder(n.left);
			PreOrder(n.right);
		}
	}
	
	public static void main(String[] args) throws Exception{
		Node n;
		System.out.println("please input the tree you want to create");
		n=createTree();
		
		
		breadthTravel(n);
		PreOrder(n);
	}
	
	
}
二叉树还可以用数组去存储,不过对于非完全二叉树会造成空间的浪费。这里的实现方式和c经典的树的构造类似,用数据域实现了类似于指针的思想。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值