【LeetCode】No.105. Construct Binary Tree from Preorder and Inorder Traversal -- J

45 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第22天,点击查看活动详情.

题目链接:leetcode.com/problems/co…

1. 题目介绍(onstruct Binary Tree from Preorder and Inorder Traversal)

Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.

【Translate】: 给定两个整数数组preorder和inorder,其中preorder是二叉树的前序遍历,inorder是同一树的前序遍历,构造并返回二叉树。

【测试用例】:

示例1:

testcase1

示例2:

testcase2

【条件约束】:

Constraints

2. 题解

2.1 递归

原题解来自于 LeetCode 官方 Solution.

两个关键的观察结果是:

  • 前序遍历遵循 根->左->右的顺序,因此,给定前序数组Preorder,我们可以很容易地访问根,即Preorder[0]。
  • 中序遍历遵循 左->根->右的顺序,因此,如果我们知道根的位置,我们就可以递归地将整个数组拆分为两个子树。

效果图如下图所示: Always use the next element in preorder to initialize a root.

/**
 * 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 {
    int preorderIndex;
    Map<Integer, Integer> inorderIndexMap;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        preorderIndex = 0;
        // build a hashmap to store value -> its index relations
        inorderIndexMap = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            inorderIndexMap.put(inorder[i], i);
        }

        return arrayToTree(preorder, 0, preorder.length - 1);
    }

    private TreeNode arrayToTree(int[] preorder, int left, int right) {
        // if there are no elements to construct the tree
        if (left > right) return null;

        // select the preorder_index element as the root and increment it
        TreeNode root = new TreeNode();
        root.val = preorder[preorderIndex++];

        // build left and right subtree
        // excluding inorderIndexMap[rootValue] element because it's the root
        root.left = arrayToTree(preorder, left, inorderIndexMap.get(root.val) - 1);
        root.right = arrayToTree(preorder, inorderIndexMap.get(root.val) + 1, right);
        return root;
    }
}

act1

3. 相关题目

3.1 知道两个排序遍历,构造一棵二叉树

知道前序遍历和中序遍历可以唯一确定一棵二叉树 知道中序遍历和后序遍历可以唯一确定一棵二叉树 知道层次遍历和中序遍历可以唯一确定一棵二叉树 知道前序遍历和后序遍历不能唯一确定一棵二叉树

[1] Java实现leetcode-106.根据中序遍历和后序遍历构造二叉树

3.2 知道两个排序遍历,求另一排序遍历

[1] 根据后序和中序遍历输出先序遍历 (java)

[2] 已知先序遍历和中序遍历,如何求后续遍历

[3] 已知某二叉树的先序和后序遍历,求有几种中序遍历的情况(有多少种二叉树的可能)