2
头图

Traverse the sequence from the middle order and the post order to construct a binary tree

Title description: Construct a binary tree based on the middle order traversal and post-order traversal of a tree.

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

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution 1: Recursion

According to the properties of middle-order traversal and post-order traversal, the solution is solved by recursion. The recursive process is as follows:

  • First, if the middle order traversal sequence or the post-order traversal sequence is empty, return the empty tree directly;
  • Because the last value of the post-order traversal sequence is the root node, first get the current root node root according to this initialization;
  • Then according to the position of the root node root in the middle-order traversal sequence, the value in front of the root node is the left subtree node of the current root node, and the number of left and right subtree nodes of the current root node is obtained;
  • Then get the left and right subtrees of the current root node by calling the recursive method;
  • Finally, return to root is the restored tree.
import com.kaesar.leetcode.TreeNode;

import java.util.Arrays;

public class LeetCode_106 {
    public static TreeNode buildTree(int[] inorder, int[] postorder) {
        // 如果中序遍历序列或后序遍历序列为空,直接返回空树
        if (inorder == null || inorder.length == 0) {
            return null;
        }
        // 后序遍历序列的最后一个值为根结点的值
        int rootVal = postorder[postorder.length - 1];
        TreeNode root = new TreeNode(rootVal);
        int leftCount = 0;
        // 中序遍历序列前面的值为左子树的节点,得到左子树的节点数量
        for (int val : inorder) {
            if (val != rootVal) {
                leftCount++;
            } else {
                break;
            }
        }
        // 递归得到当前根节点的左右子树
        root.left = buildTree(Arrays.copyOfRange(inorder, 0, leftCount), Arrays.copyOfRange(postorder, 0, leftCount));
        root.right = buildTree(Arrays.copyOfRange(inorder, leftCount + 1, inorder.length), Arrays.copyOfRange(postorder, leftCount, inorder.length - 1));
        return root;
    }

    public static void main(String[] args) {
        // 测试用例
        // 中序遍历序列
        int[] inorder = new int[]{9, 3, 15, 20, 7};
        // 后序遍历序列
        int[] postorder = new int[]{9, 15, 7, 20, 3};
        buildTree(inorder, postorder).print();
    }
}
[Daily Message] Fate is responsible for shuffling the cards, but we are playing cards!

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!