Leetcode 106. 从中序与后序遍历序列构造二叉树

题目链接

https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/

题目描述

根据一棵树的中序遍历与后序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]

返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

题解

本题和已知前序遍历和中序遍历构造二叉树一样,递归构造即可。

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    Map<Integer, Integer> map = new HashMap<>();
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (inorder == null || inorder.length == 0) { return null; }
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return buildTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
    }
    
    public TreeNode buildTree(int[] a, int a1, int a2, int[] b, int b1, int b2) {
        if (a1 > a2 || b1 > b2) { return null; }
        int mid = map.get(b[b2]);
        int count = mid - a1;
        TreeNode root = new TreeNode(b[b2]);
        root.left = buildTree(a, a1, mid - 1, b, b1, b1 + count - 1);
        root.right = buildTree(a, mid + 1, a2, b, b1 + count, b2 - 1);
        return root;
    }
}

posted @ 2018-09-07 13:30  DCREN  阅读(932)  评论(0编辑  收藏  举报