0106. Construct Binary Tree from Inorder and Postorder Traversal (M)

Construct Binary Tree from Inorder and Postorder Traversal (M)

题目

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

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

For example, given

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

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

题意

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

思路

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


代码实现

Java

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

    private TreeNode buildTree(Map map, int inI, int inJ, int[] postorder, int postI, int postJ) {
        // 递归边界
        if (postI > postJ) {
            return null;
        }
        if (postI == postJ) {
            return new TreeNode(postorder[postJ]);
        }

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

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

        return root;
    }
}

JavaScript

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {number[]} inorder
 * @param {number[]} postorder
 * @return {TreeNode}
 */
var buildTree = function (inorder, postorder) {
  return dfs(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1)
}

let dfs = function (inorder, inL, inR, postorder, postL, postR) {
  if (inL > inR) {
    return null
  }

  let last = postorder[postR]
  let root = new TreeNode(last)
  let pos = inL
  while (inorder[pos] !== last) {
    pos++
  }
  root.left = dfs(inorder, inL, pos - 1, postorder, postL, postL + pos - inL - 1)
  root.right = dfs(inorder, pos + 1, inR, postorder, postL + pos - inL, postR - 1)

  return root
}

你可能感兴趣的:(0106. Construct Binary Tree from Inorder and Postorder Traversal (M))