二叉树——根据中序和后续重建二叉树,并以先序返回

这篇文章就不废话了,主要用于日后复习,注释还待改进,若有疑问可下方留言交流

import java.util.HashMap;
import java.util.Scanner;

public class Main2 {

	public class TreeNode{
		private TreeNode left;
		private TreeNode right;
		private char val;
		
		public TreeNode(char val) {
			this.val = val;
		}
	}
	
	
	public TreeNode reConstructBinaryTree(String mid,String last) {
		TreeNode root = reConstruct(mid,0, mid.length()-1, last, 0, last.length()-1);
		return root;
	}

	
	public TreeNode reConstruct(String mid,int satrtMid,int endMid,String last,int startLast,int endLast) {
		if (satrtMid > endMid || startLast > endLast) {
			return null;
		}
		TreeNode root = new TreeNode(last.charAt(endLast));
		
		int i = satrtMid;
		while(mid.charAt(i) != last.charAt(endLast)) {
			i++;
		}
		root.left = reConstruct(mid, satrtMid, i-1,last, startLast, endLast+i-1-endMid);
		root.right = reConstruct(mid, i+1,endMid, last, i+endLast-endMid, endLast-1);
		
		return root;
	}
	
	
	//前序遍历
	public void firstRead(TreeNode root) {
		if (root == null) {
			return;
		}
		System.out.print(root.val);
		if(root.left != null) {
			firstRead(root.left);
		}
		if(root.right != null) {
			firstRead(root.right);
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in = new Scanner(System.in);
		String mid = in.nextLine();
		String last = in.nextLine();
		
		Main2 main2 = new Main2();
		TreeNode newroot = main2.reConstructBinaryTree(mid, last);
		main2.firstRead(newroot);
		//EBADCFHGIKJ中序:ABCDEFGHIJK后序
		//EBADCFHGIKJ
		//ABCDEFGHIJK
	}

}
发布了93 篇原创文章 · 获赞 26 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_38261445/article/details/100849223