二叉树遍历的递归与非递归实现
本次测试实现了二叉树先序遍历的递归与非递归实现,并测试了其性能,测试结果如预先考虑的一致,就是非递归的性能要不递归的性能高。
同时也实现了二叉树的广度优先的遍历,通过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");
}
}