给一个二叉树的前序和中序序列,求二叉树的层序序列

import java.util.Scanner;

class Node {
	char value;
	Node left;
	Node right;
	int signal;
	
	public Node() {}
	public Node(char value, Node left, Node right, int signal) {
		super();
		this.value = value;
		this.left = left;
		this.right = right;
		this.signal = signal;
	}
	public int getValue() {
		return value;
	}
	public void setValue(char value) {
		this.value = value;
	}
	public Node getLeft() {
		return left;
	}
	public void setLeft(Node left) {
		this.left = left;
	}
	public Node getRight() {
		return right;
	}
	public void setRight(Node right) {
		this.right = right;
	}
	
}

public class Main {
	
	static int k = 0;
	
	private static void layerOrder(Node root) {
		if(root == null) 
			return ;
		Node[] q = new Node[k];
		char[] r = new char[k];
		int start = 0, end = 1;
		q[start] = root;
		
		while(start < end && start < k) {
			r[start] = q[start].value;
			if(q[start].left != null) 
				q[end++] = q[start].left;
			if(q[start].right != null) 
				q[end++] = q[start].right;
			start++;
		}
		System.out.println(new String(r));
	}
	
	
	private static Node findLayers(char[] prc, char[] inc, int low, int high) {
		if(low > high) 
			return null;
		Node root = new Node();
		
		char tmp_root = prc[k++];
		root.setValue(tmp_root);

		int position_root_in_In = -1;
		for( int i = low; i <= high; i++ ) {
			if(tmp_root == inc[i]) {
				position_root_in_In = i;
				break;
			}
		}
		Node l = findLayers(prc,inc,low,position_root_in_In-1);
		Node r = findLayers(prc,inc,position_root_in_In+1,high);
		root.setLeft(l);
		root.setRight(r);
		return root;	
	}
	
	
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		while(sc.hasNext()) {
			k = 0;
			
			String pr = sc.nextLine();
			String post = sc.nextLine();
			
			int len = pr.length();
			char[] prc = pr.toCharArray();
			char[] inc = post.toCharArray();
			char[] layer = new char[len];
			
			Node root = new Node();
			root.setValue(prc[0]);
			root.setLeft(null);
			root.setRight(null);
			
			Node tree = findLayers(prc,inc,0,len-1);
			layerOrder(tree);
		}
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值