码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_106_Construct Binary Tree from Inorder and Postorder Traversal

时间:2015-04-03 15:16:31      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:中序   后序   重建二叉树   

描述:

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;
	}
}

结果:

技术分享


leetcode_106_Construct Binary Tree from Inorder and Postorder Traversal

标签:中序   后序   重建二叉树   

原文地址:http://blog.csdn.net/mnmlist/article/details/44855457

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!