其他分享
首页 > 其他分享> > 面试题:105. 从前序与中序遍历序列构造二叉树

面试题:105. 从前序与中序遍历序列构造二叉树

作者:互联网

给定一棵树的前序遍历 preorder 与中序遍历  inorder。请构造二叉树并返回其根节点。

示例 1:

 


Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
示例 2:

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        // 存放中序链表的值和index
        Map<Integer,Integer> map = new HashMap<>();
        for(int i = 0; i<inorder.length; i++) {
            map.put(inorder[i], i);
        }  

        return buildTree(preorder, 0, preorder.length -1, 0, inorder.length -1, map);
      
    }


    public TreeNode buildTree(int[] preorder, int preStart,int preEnd,int inStart,int inEnd, Map<Integer,Integer> map) {
        if(preStart > preEnd || inStart > inEnd) {
            return null;
        }

        // 计算当前值在中序遍历中index位置
        TreeNode root = new TreeNode(preorder[preStart]);
        int index = map.get(root.val);
        // index - inStart 是左子树的长度,  index - inStart + preStart是对应前序数组索引位置;而中序数组只是从index位置前移一位
        root.left = buildTree(preorder, preStart + 1, index - inStart + preStart, inStart, index -1, map);
        // index - inStart + preStart + 1前序右移一位, 而中序index位置后移一位
        root.right = buildTree(preorder, index - inStart + preStart + 1, preEnd, index + 1, inEnd, map) ;

        return root;
    }
}

 

标签:index,面试题,TreeNode,val,preStart,int,中序,inStart,二叉树
来源: https://blog.csdn.net/MrLiar17/article/details/119177231