1、二叉树先序非递归遍历思想
<1>初始化设置一个堆栈;
<2>把根节点指针入栈;
<3>当栈非空时,循环执行步骤3-1到步骤3-3
3-1:出栈取得栈顶节点,访问该节点;
3-2:若该节点的右孩子节点非空,则将该节点的右孩子节点指针入栈;
3-3:若该节点的左孩子节点非空,则将该节点的左孩子节点指针入栈;
<4>算法结束
2、中序非递归遍历思想
<1> 初始化栈,根节点入栈
<2> 若栈非空,则栈顶节点的左孩子依次进栈。直到null,则<3>
<3> 访问栈顶节点,使栈顶节点出栈。若栈顶节点右孩子非空,则使右孩子进栈成为栈顶节点。重复<2>至栈空。
初始化二叉树如图所示:
步骤如下:
至此,中序输出顺序为:D->B->H->E->I->A->F->C->G
程序代码如下:
public class BinaryNode<E> {
public E data;
public BinaryNode<E> left,right;
public BinaryNode(E data,BinaryNode<E> left,BinaryNode<E> right){
this.data = data;
this.left = left;
this.right = right;
}
public BinaryNode(E data){
this(data,null,null);
}
public BinaryNode(){
this(null,null,null);
}
public boolean isLeaf(){
return this.left == null && this.right == null;
}
public String toString(){
return this.data.toString();
}
}
public class LinkedStack<E> implements SStack<E> {
private Node<E> top;
public LinkedStack(){
this.top = null;
}
public boolean isEmpty() {
return this.top == null;
}
public boolean push(E element) {
if(element == null){
return false;
}
this.top = new Node(element,this.top);
return true;
}
public E pop() {
if(!isEmpty()){
E temp = this.top.data;
this.top = this.top.next;
return temp;
}
return null;
}
public E get() {
if(!isEmpty()){
return this.top.data;
}
return null;
}
}
public class BinaryTree<E> {
protected BinaryNode<E> root;
public BinaryTree(){
root = null;
}
public BinaryTree(BinaryNode<E> root){
this.root = root;
}
/**
* 中序非递归遍历
*/
public void nonRecInorder(){
System.out.println("中根次序非递归遍历:");
LinkedStack<BinaryNode<E>> stack = new LinkedStack<BinaryNode<E>>();
BinaryNode<E> p = this.root;
while(p != null || !stack.isEmpty()){
if(p != null){
stack.push(p);
p = p.left;
}else{
p = stack.pop();
System.out.println(p.data + " ");
p = p.right;
}
System.out.println();
}
}
}