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

给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。

解答

通过前序遍历和中序遍历得到二叉树:

  1. 从前序遍历数组头部获得根节点
  2. 从中序遍历数组中获取根节点的左子树和右子树
  3. 中序遍历数组的用处:左子树数组为空则左子节点为 null,右子树数组为空则右子节点为 null

    1. /**
    2. * Definition for a binary tree node.
    3. * function TreeNode(val, left, right) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.left = (left===undefined ? null : left)
    6. * this.right = (right===undefined ? null : right)
    7. * }
    8. */
    9. /**
    10. * @param {number[]} preorder
    11. * @param {number[]} inorder
    12. * @return {TreeNode}
    13. */
    14. var buildTree = function(preorder, inorder) {
    15. if (preorder.length && inorder.length) {
    16. const rootVal = preorder.shift();
    17. let rootIndex = inorder.indexOf(rootVal);
    18. const root = new TreeNode(rootVal);
    19. root.left = buildTree(preorder, inorder.slice(0, rootIndex));
    20. root.right = buildTree(preorder, inorder.slice(rootIndex + 1));
    21. return root;
    22. } else {
    23. return null;
    24. }
    25. };