您的位置:首页 > 编程语言 > PHP开发

FTPrep, 106 Construct Binary Tree from Inorder and Postorder Traversal

2017-10-07 12:41 316 查看
和105 是一个道理,套路是一样一样的。

代码:

/**
* 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) {
if(inorder.length==0 || postorder.length==0) return null;
HashMap<Integer, Integer> indexInInorderMap= new HashMap<>();
for(int i =0; i<inorder.length; i++) indexInInorderMap.put(inorder[i], i);
return constructTree(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1, indexInInorderMap);
}

private TreeNode constructTree(int[] inorder, int inLeft, int inRight, int[] postorder, int postLeft, int postRight, HashMap<Integer, Integer> map){
if(inLeft>inRight || postLeft>postRight) return null;
int rootIndexInInorder= map.get(postorder[postRight]);
TreeNode root=new TreeNode(postorder[postRight]);
root.left=constructTree(inorder, inLeft, rootIndexInInorder-1, postorder, postLeft, postLeft+rootIndexInInorder-inLeft-1, map);
root.right=constructTree(inorder, rootIndexInInorder+1, inRight , postorder, postLeft+rootIndexInInorder-inLeft, postRight-1, map);
return root;
}
}

// 关键之处!!!重中之重,就是递归时候的 左右index,inorder里面的index的好划分,因为就是一刀切,分两边。容易错的是:preorder/postorder里的片段是根据inorder里的左右两边长度来划分的,所以!!一定要长度相等,一定长度相等!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐