【LeetCode】 106. Construct Binary Tree from Inorder and Postorder Traversal Construct a binary tree from the inorder and postorder traversal sequence (JAVA)

【LeetCode】 106. Construct Binary Tree from Inorder and Postorder Traversal Construct a binary tree (Medium) from the inorder and postorder traversal sequence (JAVA)

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

Title description:

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

Topic

The binary tree is constructed according to the middle-order traversal and post-order traversal of a tree.

Note:
You can assume that there are no duplicate elements in the tree.

Problem solving method

Same as the previous question, except that the properties of preorder traversal and postorder traversal are different: [LeetCode] 105. Construct Binary Tree from Preorder and Inorder Traversal Construct Binary Tree from Preorder and Inorder Traversal (JAVA)

1. The root node of the post-order traversal is the last; the root node of the middle-order traversal is in the middle. If the root node is found, it can be divided into left and right subtrees.
2. Iteratively update the complete tree

/**
 * 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) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return bH(inorder, postorder, map, 0, inorder.length - 1, 0, postorder.length - 1);
    }

    public TreeNode bH(int[] inorder, int[] postorder, Map<Integer, Integer> map, int iStart, int iEnd, int pStart, int pEnd) {
        if (iStart > iEnd || pStart > pEnd) return null;
        TreeNode root = new TreeNode(postorder[pEnd]);
        int mid = map.get(postorder[pEnd]);
        root.left = bH(inorder, postorder, map, iStart, mid - 1, pStart, pStart + mid - iStart - 1);
        root.right = bH(inorder, postorder, map, mid + 1, iEnd, pStart + mid - iStart, pEnd - 1);
        return root;
    }
}

Execution time: 3 ms, defeated 76.80% of users
in all Java submissions Memory consumption: 40.4 MB, defeated 61.90% of users in all Java submissions

Guess you like

Origin blog.csdn.net/qq_16927853/article/details/105823524