题目链接:https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
思路同上一篇LeetCode105
只不过后续遍历是从后往前来确定根节点的,然后在inorder中找到root节点对应的下标。
如果不太理解下标的对应关系,可以先用例子:
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
当在postorder中找到最后一个3,它是root节点,在inorder中对应index是1,然后inorder就被分割成了两部分,
左侧部分产生左子树,右侧部分产生右子树。依次递归下去,难点在于index与下一个递归边界的判断。
AC 8ms Java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
return helper(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
}
public TreeNode helper(int[] inorder,int inStart,int inEnd,
int[] postorder,int poStart,int poEnd){
if(inStart>inEnd||poStart>poEnd)
return null;
TreeNode root=new TreeNode(postorder[poEnd]);
int index=0;
for(int i=inStart;i<=inEnd;i++){
if(inorder[i]==root.val){
index=i;
break;
}
}
root.left=helper(inorder,inStart,index-1,postorder,poStart,poStart+index-inStart-1);
root.right=helper(inorder,index+1,inEnd,postorder,poEnd-(inEnd-index),poEnd-1);
return root;
}
}