利用先序和中序非遞歸生成二叉樹(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);
}
 
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章