题解 | #重建二叉树#

重建二叉树

http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6

import java.util.*;
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
     //记录中序遍历数组的值对应下标
    Map<Integer,Integer> map = new HashMap<>();
    public TreeNode reConstructBinaryTree(int [] pre,int [] vin) {
        if(pre == null||pre.length == 0){
            return null;
        }
        for(int i = 0;i<vin.length;i++){
            map.put(vin[i],i);
        }
        return binaryTree(pre,0,pre.length-1,vin,0,vin.length-1);
        
    }
    //后序遍历
    public TreeNode binaryTree(int[] pre,int preLeft,int preRight,int[] vin,int vinLeft,int vinRight){
        if(preLeft > preRight){
            return null;
        }
        TreeNode root = new TreeNode(pre[preLeft]);
        int index = map.get(pre[preLeft]);
        int size = index-vinLeft;
        root.left = binaryTree(pre,preLeft+1,preLeft+size,vin,vinLeft,index-1);
        root.right = binaryTree(pre,preLeft+size+1,preRight,vin,index+1,vinRight);
        return root;
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
头像
07-26 14:05
门头沟学院 Java
欧贺桥:哈哈哈哈哈笑死我了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务