leetcode_106_Construct Binary Tree from Inorder and Postorder Traversal

描述:

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

思路:

1.将中序遍历序列和其对应的下标存储到一个map中,方便下面的查找
2.递归选取后序序列的倒数第一个元素作为树的根节点,然后查找根节点在 后序序列中位置inorderIndex,endInorder-inorderIndex可以得到右子树的长度
3.根据右子树的长度和endPreOrder可以求出 后序序列中右子树的起始位置
4.从上面可以求出左右子树的 后序序列和中序序列的起始位置,递归调用建树过程即可。

代码:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    int[] ArrPostorder;
	int[] ArrInorder;
	Map<Integer, Integer> mapInorder = new HashMap<Integer, Integer>();
	public TreeNode buildTree(int[] inorder, int[] postorder) {
		if (inorder.length == 0 || inorder == null)
			return null;
		ArrPostorder = postorder;
		ArrInorder = inorder;
		for (int i = 0; i < inorder.length; i++)
			mapInorder.put(inorder[i], i);
		int start = 0, end = postorder.length - 1;
		TreeNode root = new TreeNode(0);
		createTree(root, start, end, start, end);
		return root;
	}

	public void createTree(TreeNode root, int start1, int end1, int start2,int end2) {
		int subStart1,subStart2,subEnd1,subEnd2;
		int target = ArrPostorder[end2];
		int indexInOrder = mapInorder.get(target);
		int len = end1-indexInOrder;
		int indexPostOrder = end2-len;
		if (start1 <= indexInOrder - 1) {
			subEnd1 = indexInOrder-1;
			subEnd2 = indexPostOrder - 1;
			root.left = new TreeNode(0);
			createTree(root.left, start1, subEnd1, start2, subEnd2);
		}
		root.val = target;
		if (indexInOrder + 1 <= end1) {
			subStart1 = indexInOrder + 1;
			subStart2 = indexPostOrder;
			subEnd2=end2-1;
			root.right = new TreeNode(0);
			createTree(root.right, subStart1, end1, subStart2, subEnd2);
		}
		return;
	}
}

结果:



你可能感兴趣的:(后序,中序,重建二叉树)