题目链接:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
题目描述:根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
解答
通过递归建立二叉树
时间复杂度:O(N),空间复杂度:O(N)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
//rootIndex表示每次从postorder中获得的根结点的下标
int rootIndex ;
//indexMap 中存储inorder中的值和它们的下标的对应关系
Map<Integer,Integer> indexMap = new HashMap<>();
public TreeNode buildTree(int[] inorder, int[] postorder) {
//判断临界条件
if(inorder == null || postorder ==null || inorder.length<=0 || postorder.length<=0){
return null;
}
//将inorder中的值和它们的下标的对应关系存入map
for(int i=0;i<inorder.length;i++){
indexMap.put(inorder[i],i);
}
//从后序遍历数组的最后一个元素开始,是第一个根结点
rootIndex = postorder.length-1;
//调用helper来建立二叉树
return helper(inorder,postorder,0,postorder.length-1);
}
public TreeNode helper(int[] inorder,int[] postorder,int left,int right) {
//终止条件
if(left>right) {
return null;
}
//当前层做的事情
//新建一个结点存储遍历到的根结点
TreeNode root = new TreeNode(postorder[rootIndex]);
//获取这个根结点在inorder中的下标index
int index = indexMap.get(postorder[rootIndex]);
//rootIndex减1,指向下一个要找的根结点
rootIndex--;
//下一层要做的事情
//根据index将inorder分成右部分和左部分,分别对应右子树和左子树
root.right=helper(inorder,postorder,index+1,right);
root.left = helper(inorder,postorder,left,index-1);
return root;
}
}