剑指offer_重建二叉树

根据二叉树的前序遍历和中序遍历的结果,重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的 数字。

前序遍历的第一个值为根节点的值,使用这个值将中序遍历结果分成两部分,左部分为树的左子树中序遍历结果,右 部分为树的右子树中序遍历的结果。

 1 import java.util.HashMap;
 2 import java.util.Map;
 3 public class Solution {
 4     private Map<Integer, Integer> indexForInOrders = new HashMap<>();
 5     public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
 6         for (int i = 0; i < in.length; i++)
 7         indexForInOrders.put(in[i], i);
 8         return reConstructBinaryTree(pre, 0, pre.length - 1, 0 );
 9     }
10     private TreeNode reConstructBinaryTree(int[] pre, int preL, int preR, int inL) {
11     if (preL > preR)
12     return null;
13     TreeNode root = new TreeNode(pre[preL]);
14     int inIndex = indexForInOrders.get(root.val);
15     int leftTreeSize = inIndex - inL;
16     root.left = reConstructBinaryTree(pre, preL + 1, preL + leftTreeSize, inL );
17     root.right = reConstructBinaryTree(pre, preL + leftTreeSize + 1, preR, inL +leftTreeSize + 1);
18     return root;
19 }
20 
21 }

 

posted @ 2019-08-10 20:36  chyblogs  阅读(139)  评论(0)    收藏  举报