标签:pat java linkedlist 二叉树的遍历
算法思路:
1、后序最后元素为根,根将中序分为左右子树
2、层序遍历利用队列实现,java使用LinkedList
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; class Node{ int key; Node left; Node right; public Node(int key){ this.key=key; } } public class Main { static int num; static int post[]; static int in[]; public static Node createBT(int postH, int postT, int inH, int inT){ if(postH>=postT)return null; int key=post[postT-1]; Node root=new Node(key); int i=inH; for(;i<inT;i++) if(key==in[i])break; root.left=createBT(postH,i-inH+postH,inH,i); root.right=createBT(i-inH+postH,postT-1,i+1,inT); return root; } public static void levelTr(Node root){ Queue<Node> que=new LinkedList<Node>(); if(null!=root)System.out.print(root.key); if(null!=root.left)que.offer(root.left); if(null!=root.right)que.offer(root.right); while(!que.isEmpty()){ Node node=que.poll(); System.out.print(" "+node.key); if(null!=node.left)que.offer(node.left); if(null!=node.right)que.offer(node.right); } } public static void main(String[] args){ Scanner sc=new Scanner(System.in); num=sc.nextInt(); post=new int[num]; in=new int[num]; for(int i=0;i<num;i++) post[i]=sc.nextInt(); for(int i=0;i<num;i++) in[i]=sc.nextInt(); Node root=createBT(0,num,0,num); levelTr(root); sc.close(); } }
标签:pat java linkedlist 二叉树的遍历
原文地址:http://blog.csdn.net/ldrmcml/article/details/44150997