【LeetCode】【HOT】105. 从前序与中序遍历序列构造二叉树(哈希表+递归)

【LeetCode】【HOT】105. 从前序与中序遍历序列构造二叉树

文章目录

  • 【LeetCode】【HOT】105. 从前序与中序遍历序列构造二叉树

【LeetCode】【HOT】105. 从前序与中序遍历序列构造二叉树(哈希表+递归)_第1张图片
【LeetCode】【HOT】105. 从前序与中序遍历序列构造二叉树(哈希表+递归)_第2张图片

package hot;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;

class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int val){
        this.val = val;
    }
}

public class Solution105 {
    public static void main(String[] args) {
        int[] preorder = {3,9,20,15,7};
        int[] inorder = {9,3,15,20,7};
        Solution105 solution = new Solution105();
        System.out.println(solution.levelOrder(solution.method(preorder, inorder)));
    }

    int[] preorder;
    HashMap<Integer, Integer> dic = new HashMap<>();

    private TreeNode method(int[] preorder, int[] inorder){
        this.preorder = preorder;
        for(int i = 0; i < inorder.length; i++){
            dic.put(inorder[i], i);
        }
        return recur(0, 0, inorder.length-1);
    }

    private TreeNode recur(int root, int left, int right){
        if(left > right) return null;
        TreeNode node = new TreeNode(preorder[root]);
        int i = dic.get(preorder[root]);
        node.left = recur(root + 1, left, i - 1);
        node.right = recur(root + i - left + 1, i + 1, right);
        return node;
    }

    private ArrayList<Integer> levelOrder(TreeNode root){
        ArrayList<Integer> res = new ArrayList<>();
        ArrayDeque<TreeNode> queue = new ArrayDeque<>();
        TreeNode temp = new TreeNode(0);
        queue.add(root);
        while(!queue.isEmpty()){
            temp = queue.poll();
            res.add(temp.val);
            if(temp.left != null) queue.add(temp.left);
            if(temp.right != null) queue.add(temp.right);
        }
        return res;
    }
}

//时间复杂度为 O(n)
//空间复杂度为 O(n)

你可能感兴趣的:(LeetCode,LeetCode)