java用中根后根序列构造二叉树,106. 从中序与后序遍历序列构造二叉树
題目描述
根據(jù)一棵樹的中序遍歷與后序遍歷構(gòu)造二叉樹。
注意:
你可以假設(shè)樹中沒有重復(fù)的元素。
示例:
例如,給出
中序遍歷 inorder = [9,3,15,20,7]
后序遍歷 postorder = [9,15,7,20,3]
返回如下的二叉樹:
3
/ \
9 20
/ \
15 7
思路
1.思路與105. 從前序與中序遍歷序列構(gòu)造二叉樹基本一致。
2.在二叉樹后序遍歷的數(shù)組中,找到根的位置。
3.然后中序遍歷的數(shù)組中根據(jù)根的值,找到左子樹和右子樹的分割點(diǎn),遞歸下去即可。
Java代碼實(shí)現(xiàn)
public TreeNode buildTree(int[] inorder, int[] postorder) {
return buildTree(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
}
public TreeNode buildTree(int[] inorder,int inStart,int inEnd, int[] postorder,int postStart,int postEnd) {
if(inStart > inEnd || postStart > postEnd)
return null;
//根的值
int rootVal = postorder[postEnd];
int i;
for (i = 0; i <= inEnd - inStart; i++) {
if(inorder[inStart+i] == rootVal)
break;
}
TreeNode root = new TreeNode(rootVal);
root.left = buildTree(inorder,inStart,inStart+i-1,postorder,postStart,postStart+i-1);
root.right = buildTree(inorder,inStart+i+1,inEnd,postorder,postStart+i,postEnd-1);
return root;
}
總結(jié)
以上是生活随笔為你收集整理的java用中根后根序列构造二叉树,106. 从中序与后序遍历序列构造二叉树的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 完全备份恢复吗_mysql完
- 下一篇: python创建二维空列表_python