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

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值