根据一棵树的后序遍历与中序遍历构造二叉树
思路及实现:
1.先遍历后序,从尾巴开始倒着遍历(倒数第一个元素为根节点)
2.找到后序遍历的节点在中序当中的位置
3.一直去遍历后序
从后向前遍历后序遍历数组;
拿到后序遍历的倒数第一个节点,new一个节点出来让其成为根节点;
找到在中序遍历数组中该节点的位置,左边就是左子树,右边就是右子树;
继续上述查找,直到后序遍历结果的数组全部遍历完。
public int posIndex = 0;
public Node buildTreeChild2 (int[] postorder,int[] inorder,int inbegin,int inend){
if(inbegin > inend){
return null;
}
Node root = new Node(postorder[posIndex]);
int rootIndex = findInorderIndex(inorder,inbegin,inend,postorder[posIndex]);
if(rootIndex == -1){
return null;
}
posIndex--;
root.right = buildTreeChild2(postorder,inorder,rootIndex+1,inend);
root.left = buildTreeChild2(postorder,inorder,inbegin,rootIndex-1);
return root;
}
public Node buildTree2 (int[] postorder,int[] inorder){
if(postorder.length == 0 || inorder.length == 0){
return null;
}
posIndex = postorder.length-1;
return buildTreeChild2(postorder,inorder,0,inorder.length-1);
}