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.
Subscribe to see which companies asked this question.
题目简述:
输入中序遍历和后序遍历的数组,要求重构二叉树并返回二叉树根节点。
思路分析:
1.前序遍历,中序遍历和后序遍历只要知道中序遍历加其他任意一个能唯一确定一棵二叉树
2.使用Hash表建立中序遍历的索引,让时间复杂度从O(N^2)->O(N).空间复杂度O(1)->O(N)
复杂度:
时间复杂度O(N)
空间复杂度O(N)
代码:
public class Solution {
int count;
public TreeNode buildTree(int[] inorder, int[] postorder) {
TreeNode aNode =null;
if(inorder.length == 0){
return null;
}else{
aNode =new TreeNode(postorder[postorder.length-1]);
//aNode.val = ;
}
Map<Integer,Integer> aMap = createIndex(inorder);
count = inorder.length-2;
//传入的部分都是未使用过的元素
aNode.right = createSubTree(aMap.get(aNode.val)+1,inorder.length-1,postorder,aMap);
aNode.left = createSubTree(0,aMap.get(aNode.val)-1,postorder,aMap);
return aNode;
}
public TreeNode createSubTree(int start,int end,int[] postorder,Map<Integer,Integer> aMap){
if(start>end){
return null;
}
TreeNode aNode = new TreeNode(postorder[count--]);
aNode.right = createSubTree(aMap.get(aNode.val)+1,end,postorder,aMap);
aNode.left = createSubTree(start,aMap.get(aNode.val)-1,postorder,aMap);
return aNode;
}
public Map<Integer,Integer> createIndex(int[] inorder){
Map<Integer,Integer> aMap =new HashMap<>();
for(int i=0;i<inorder.length;i++){
aMap.put(inorder[i],i);
}
return aMap;
}
}
结果:
65%