2015年2月25日

二叉树遍历的递归与非递归实现

本次测试实现了二叉树先序遍历的递归与非递归实现,并测试了其性能,测试结果如预先考虑的一致,就是非递归的性能要不递归的性能高。

同时也实现了二叉树的广度优先的遍历,通过queue来实现的。

package com.pip.structure.tree;

import java.util.ArrayDeque;
import java.util.Stack;

public class MyNode {

	private int nodeValue;
	private MyNode leftNode;
	private MyNode rightNode;
	
	public MyNode(int v){
		this.nodeValue=v;
	}
	
	public void addElement(int k){
		MyNode m=new MyNode(k);
			if(k>=this.nodeValue){
				if(this.rightNode!=null){
					rightNode.addElement(k);
				}else{
				this.rightNode=m;
				}
			}else{
				if(this.leftNode!=null){
					leftNode.addElement(k);
				}else{
			     this.leftNode=m;
				}
			}
	}
	
	public void prePrint(MyNode root){
		if(root==null){
			return;
		}
		System.out.print(root.nodeValue+"/");
		prePrint(root.leftNode);
		prePrint(root.rightNode);
	}
	
	public void prePrintNonRec(MyNode root){
		Stack<MyNode> s=new Stack<MyNode>();
		s.push(root);
		while(!s.empty()){
			MyNode m=s.pop();
			System.out.print(m.nodeValue+"/");
			if(m.rightNode!=null){
				s.push(m.rightNode);
			}
			if(m.leftNode!=null){
              s.push(m.leftNode);
			}
		}
	}
	
	public void levelOrderTraversal(MyNode root){
		if(root==null){
			return;
		}
		ArrayDeque<MyNode> que=new ArrayDeque<MyNode>();
		que.add(root);
		while(!que.isEmpty()){
			MyNode m=que.poll();
			System.out.print(m.nodeValue+"/");
			if(m.leftNode!=null){
				que.add(m.leftNode);
			}
			if(m.rightNode!=null){
				que.add(m.rightNode);
			}
		}
		
		
	}
	
	
	public static void main(String[] args){
		MyNode m=new MyNode(8);
		m.addElement(3);
		m.addElement(9);
		m.addElement(14);
		m.addElement(1);
		m.addElement(15);
		m.addElement(2);
		
		m.prePrint(m);
		m.prePrintNonRec(m);
		m.levelOrderTraversal(m);
	}
	
	
	
}

性能测试代码

package com.pip.structure.tree;

import java.util.Date;

import org.junit.Test;

public class TreeTest {

	@Test
	public void testTree(){
		MyNode m=new MyNode(500);
		//add Element for the tree
		for(int i=0;i<10000;i++){
			int k=(int) Math.round(10000*Math.random());
			m.addElement(k);
		}
		
		long beforeTime = new Date().getTime();  
        m.prePrint(m);
        long afterTime = new Date().getTime();
        System.out.println();
        System.out.println("recursion-time--" + (afterTime - beforeTime) + "ms");
        
        long beforeTime2 = new Date().getTime();  
        m.prePrintNonRec(m);
        long afterTime2 = new Date().getTime();
        System.out.println();
        System.out.println("non--recursion-time--" + (afterTime2 - beforeTime2) + "ms");
	}
	
	
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值