先序、中序和后序数组两两结合重构二叉树

【题目】已知一棵二叉树的所有节点值都不同,给定这棵二叉树正确的先序、中序和后序数组。请分别用三个函数实现任意两种数组结合重构原来的二叉树,并返回重构二叉树的头结点。

public class PreInPostToBST {
	public static class Node {
		public int value;
		public Node left;
		public Node right;

		public Node(int value) {
			this.value = value;
		}
	}

	public static Node preInToTree(int[] pre, int[] in) {
		if (pre == null || in == null) {
			return null;
		}
		Map<Integer, Integer> map = new HashMap<>();
		for (int i = 0; i < in.length; i++) {
			map.put(in[i], i);
		}
		return preIn(pre, 0, pre.length - 1, in, 0, in.length - 1, map);
	}

	public static Node preIn(int[] pre, int pi, int pj, int[] in, int ni, int nj, Map<Integer, Integer> map) {
		if (pi > pj) {
			return null;
		}
		Node head = new Node(pre[pi]);
		int index = map.get(pre[pi]);
		head.left = preIn(pre, pi + 1, pi + index - ni, in, ni, index - 1, map);
		head.right = preIn(pre, pi + index - ni + 1, pj, in, index + 1, nj, map);
		return head;
	}

	public static Node posInToTree(int[] pos, int[] in) {
		if (pos == null || in == null) {
			return null;
		}
		Map<Integer, Integer> map = new HashMap<>();
		for (int i = 0; i < in.length; i++) {
			map.put(in[i], i);
		}
		return posIn(in, 0, in.length - 1, pos, 0, pos.length - 1, map);
	}

	public static Node posIn(int[] in, int ni, int nj, int[] pos, int si, int sj, Map<Integer, Integer> map) {
		if (si > sj) {
			return null;
		}
		Node head = new Node(pos[sj]);
		int index = map.get(pos[sj]);
		head.left = posIn(in, ni, index - 1, pos, si, si + index - ni - 1, map);
		head.right = posIn(in, index + 1, nj, pos, si + index - ni, sj - 1, map);
		return head;
	}

	public static Node prePosToTree(int[] pre, int[] pos) {
		if (pre == null || pos == null) {
			return null;
		}
		Map<Integer, Integer> map = new HashMap<>();
		for (int i = 0; i < pos.length; i++) {
			map.put(pos[i], i);
		}
		return prePos(pre, 0, pre.length - 1, pos, 0, pos.length - 1, map);
	}

	public static Node prePos(int[] pre, int pi, int pj, int[] pos, int si, int sj, Map<Integer, Integer> map) {

		Node head = new Node(pos[sj--]);
		if (pi == pj) {
			return head;
		}
		int index = map.get(pre[++pi]);
		head.left = prePos(pre, pi, pi + index - si, pos, si, index, map);
		head.right = prePos(pre, pi + index - si + 1, pj, pos, index + 1, sj, map);
		return head;
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值