首页 > 其他 > 详细

105. 从前序与中序遍历序列构造二叉树

时间:2020-04-12 18:52:15      阅读:48      评论:0      收藏:0      [点我收藏+]

根据一棵树的前序遍历与中序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]

返回如下的二叉树:

    3
   /   9  20
    /     15   7

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    Map<Integer,Integer> map;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        map = new HashMap<>();
        for(int i = 0;i < inorder.length;i++){
            map.put(inorder[i],i);
        }
        //分治
        return help(preorder,0,preorder.length,inorder,0,inorder.length);
        
    }
    
    private TreeNode help(int[] pre,int preI,int preJ,
                            int[] in,int inI,int inJ){
        if(preI >= preJ) return null;
        //preI为root
        int num = pre[preI];
        int index = map.get(num);
        TreeNode root = new TreeNode(num);
        TreeNode left = help(pre,preI + 1,preI + 1 + index - inI ,in,inI,index);
        TreeNode right = help(pre,preI + 1 + index - inI, preJ ,in,index + 1,inJ);
        root.left = left;
        root.right = right;
        return root;
    }
}

 

105. 从前序与中序遍历序列构造二叉树

原文:https://www.cnblogs.com/zzytxl/p/12686162.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!