利用先序和中序非递归生成二叉树(java实现)

来源:互联网 发布:淘宝客服头像女生 编辑:程序博客网 时间:2024/06/07 01:04
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;


class Node{
int number;
Node rightChild;
Node leftChild;
//构造函数
public Node(int number){
this.number=number;
}
}


public class Demo8{
public static void main(String[] args) {
int[] a={1,2,4,5,6,7,3,8};
int[] b={4,2,6,5,7,1,3,8};

Stack<Node> stack=new Stack<Node>();
stack.push(new Node('#'));
Node root=new Node(a[0]);
int a1=0,b1=0;
Node p=root;


while(a1<a.length||b1<b.length){

//完成了进栈和左孩子连接
stack.push(p);

while(a[a1]!=b[b1]){
a1+=1;
p.leftChild=new Node(a[a1]);
stack.push(p.leftChild);
p=p.leftChild;
}
//最左下角的点没有左节点了
p.leftChild=null;

a1++;b1++;

//出栈,q是出栈的数据,p是进栈的数据
Node q=stack.pop();
while(b1<b.length&&stack.lastElement().number==b[b1]){
q.rightChild=null;
q=stack.pop();
b1++;
}

if(a1<a.length||b1<b.length){
p=new Node(a[a1]);
q.rightChild=p;
}
else{
q.rightChild=null;
}

}
Print(root);
}

//使用队列,将二叉树按层,从左往右输出
public static void Print(Node root){
if (root==null)
return ;
//定义一个队列,Queue是一个接口
Queue<Node> queue=new LinkedList<Node>();
 
queue.offer(root);
while(!queue.isEmpty()){
Node temp=queue.poll();
System.out.print(temp.number+" ");
//将左孩子和右孩子分别压入
if(temp.leftChild!=null)queue.offer(temp.leftChild);
if(temp.rightChild!=null)queue.offer(temp.rightChild);
}
 
}
}
阅读全文
0 0
原创粉丝点击