描述
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
- 思路
思路与leetCode 105题很相近,可以参考我的博客:http://blog.csdn.net/qufayudao/article/details/79542158 - 代码(c#)
public TreeNode BuildTree(int[] inorder, int[] postorder) {
if (inorder.Length == 0 || postorder.Length == 0)
return null;
if (inorder.Length == 1 && postorder.Length == 1)
return new TreeNode(inorder[0]);
TreeNode node = new TreeNode(postorder[postorder.Length-1]);
int index = inorder.Length-1;
for (; index >0; index--)
{
if (inorder[index] == node.val)
{
break;
}
}
node.right = BuildTree(inorder.Skip(index+1).ToArray(), postorder.Skip(index).Take(postorder.Length-index-1).ToArray());
node.left = BuildTree(inorder.Take(index).ToArray(), postorder.Take(index).ToArray());
return node;
}