0105. Construct Binary Tree from Preorder and Inorder Traversal (M)

Construct Binary Tree from Preorder and Inorder Traversal (M)

题目

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

题意

给定一棵二叉树的先序序列和中序序列,要求重建这棵二叉树。

思路

由二叉树的性质可知,先序序列的第一个元素是当前二叉树的根节点,根节点将中序序列分为左子树和右子树。先序序列的第一个元素即为整棵二叉树的根节点,在中序序列中找到该元素,则中序中该元素左侧为左子树,右侧为右子树,依照左右子树个数又可将先序序列剩余元素进行划分,接着只要对左子树和右子树进行递归操作即可。


代码实现

Java

class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        // 为了省去在中序序列中迭代查找元素的时间, 直接用HashMap将整个inorder存进去
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return buildTree(map, preorder, 0, preorder.length - 1, 0, inorder.length - 1);
    }

    private TreeNode buildTree(Map<Integer, Integer> map, int[] preorder, int preI, int preJ, int inI, int inJ) {
        // 递归边界
        if (preI > preJ) {
            return null;
        }
        if (preI == preJ) {
            return new TreeNode(preorder[preI]);
        }

        // 在中序序列中找到先序序列的第一个元素,并求出左子树的长度
        int len = map.get(preorder[preI]) - inI;

        TreeNode root = new TreeNode(preorder[preI]);
        // 划分区域后递归处理左右子树
        root.left = buildTree(map, preorder, preI + 1, preI + len, inI, inI + len - 1);
        root.right = buildTree(map, preorder, preI + len + 1, preJ, inI + len + 1, inJ);

        return root;
    }
}

JavaScript

/**
 * @param {number[]} preorder
 * @param {number[]} inorder
 * @return {TreeNode}
 */
var buildTree = function (preorder, inorder) {
  return construct(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1)
}

var construct = function (preorder, pa, pb, inorder, ia, ib) {
  if (pa > pb) return null

  const root = new TreeNode(preorder[pa])
  const leftLen = inorder.indexOf(root.val) - ia
  root.left = construct(preorder, pa + 1, pa + leftLen, inorder, ia, ia + leftLen - 1)
  root.right = construct(preorder, pa + leftLen + 1, pb, inorder, ia + leftLen + 1, ib)

  return root
}
posted @ 2021-06-08 22:15  墨云黑  阅读(33)  评论(0编辑  收藏  举报