FTPrep, 106 Construct Binary Tree from Inorder and Postorder Traversal

来源:互联网 发布:音乐播放器源码 编辑:程序博客网 时间:2024/06/02 07:08

和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里的左右两边长度来划分的,所以!!一定要长度相等,一定长度相等!!


阅读全文
0 0
原创粉丝点击