java实现二叉树的遍历
class Note{public Note() {
}
private Note leftNote;//左节点
private Note rigthNote;//右节点
private int value;//节点出的值
//添加get/set方法
public Note getLeftNote() {
return leftNote;
}
public void setLeftNote(Note leftNote) {
this.leftNote = leftNote;
}
public Note getRigthNote() {
return rigthNote;
}
public void setRigthNote(Note rigthNote) {
this.rigthNote = rigthNote;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
//递归
//先序遍历
public voidprePass(Note note){//此处为根节点
if(null==note) return;
System.out.println(note.getValue());
prePass(note.getLeftNote());
prePass(note.getRigthNote());
}
//非递归
public void prePassNot(Note note)
{
if(null == note) return ;
Stack<Note>stack = new Stack<Note>();
stack.add(note);
while(null!=stack && stack.size()>0)
{
Note noe = stack.pop();
System.out.println(noe.getValue());
if(null!=noe.getRigthNote())stack.add(noe.getRigthNote());
if(null!=noe.getLeftNote())stack.add(noe.getLeftNote());
}
}
页:
[1]