易截截图软件、单文件、免安装、纯绿色、仅160KB

Java递归、非递归实现二叉树遍历

最近找工作做笔试题发现很重要,就自己写了一点,和大家分享
import java.util.Stack;
import java.util.HashMap;
public class BinTree {
private char date;
private BinTree lchild;
private BinTree rchild;
public BinTree(char c) {
date = c;
}
// 先序遍历递归
public static void preOrder(BinTree t) {
if (t == null) {
return;
}
System.out.print(t.date);
preOrder(t.lchild);
preOrder(t.rchild);
}
// 中序遍历递归
public static void InOrder(BinTree t) {
if (t == null) {
return;
}
InOrder(t.lchild);
System.out.print(t.date);
InOrder(t.rchild);
}
// 后序遍历递归
public static void PostOrder(BinTree t) {
if (t == null) {
return;
}
PostOrder(t.lchild);
PostOrder(t.rchild);
System.out.print(t.date);
}
// 先序遍历非递归
public static void preOrder2(BinTree t) {
Stack<BinTree> s = new Stack<BinTree>();
while (t != null || !s.empty()) {
while (t != null) {
System.out.print(t.date);
s.push(t);
t = t.lchild;
}
if (!s.empty()) {
t = s.pop();
t = t.rchild;
}
}
}
// 中序遍历非递归
public static void InOrder2(BinTree t) {
Stack<BinTree> s = new Stack<BinTree>();
while (t != null || !s.empty()) {
while (t != null) {
s.push(t);
t = t.lchild;
}
if (!s.empty()) {
t = s.pop();
System.out.print(t.date);
t = t.rchild;
}
}
}
// 后序遍历非递归
public static void PostOrder2(BinTree t) {
Stack<BinTree> s = new Stack<BinTree>();
Stack<Integer> s2 = new Stack<Integer>();
Integer i = new Integer(1);
while (t != null || !s.empty()) {
while (t != null) {
s.push(t);
s2.push(new Integer(0));
t = t.lchild;
}
while (!s.empty() && s2.peek().equals(i)) {
s2.pop();
System.out.print(s.pop().date);
}
if (!s.empty()) {
s2.pop();
s2.push(new Integer(1));
t = s.peek();
t = t.rchild;
}


相关文档:

Java基础知识——JNI入门经典

JNI是Java Native Interface的缩写,通过使用native方法,Java可以调用本地C/C++子程序。声明一个本地子程序的方法是:在方法名前添加native修饰,如
public native void myfun();
调用该子程序的方法为:
static{
    System.loadLibrary("myfun");
}
在Windows上,上面的myfun即指包含用C/C++写的my ......

JAVA笔试题

第一:
1.String是最基本的数据类型么?
答:不是。基本的数据类型包括:byte,int,char,long,float,double,boolean和short.
java.lang.String类是final类型的,因此不可以继承这个类,不能修改这个类。
2.静态变量和实例变量的区别?
答:static i = 10 ;//常量  
      &nb ......

java中List集合的使用

 在Java中如果List 结合存取的是许多类型不同的数据如int,String 类型都有,那么如何使用JSTL表达式循环获取List集合中的元素呢?
如:假如List list=new ArrayList();    int a=1; String b="sss";    String c="ddddddd";……在Servlet中 使用Session 保存
session.set ......

Java中利用final关键字inline编译优化真的有效吗?

  为寻求java代码的性能优化,从网上搜到利用final关键字进行编译时inline优化的方法,但是真的有效吗?实际测试中发现未必,甚至性能影响巨大,最终放弃了使用final优化的想法。
  测试环境:Windows XP SP2,JDK 1.6.0_15-b03,Eclipse 3.5 SR1。
package test;
public class Test {
public static void main(St ......

Java集合类List/Set/Map的区别和联系

 
一、Array , Arrays
Java所有“存储及随机访问一连串对象”的做法,array是最有效率的一种。
1、
效率高,但容量固定且无法动态改变。
array还有一个缺点是,无法判断其中实际存有多少元素,length只是告诉我们array的容量。
2、Java中有一个Arrays类,专门用来操作array。
   
a ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号