Jianzhi offer interview questions 07. Rebuilding Binary Tree

Title address

https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/submissions/

Ideas

The idea of ​​construction is to first know who the root is, then build the left side, and then build the right side.
Put each node of the middle order in the map first so that you can know the subscript of each node
. It is because the root node can be known from the first order traversal result. The left side of the root node in the middle order traversal is the node on the left of the binary tree,
the data on the right is the node on the right of the binary tree, and then it can be created recursively

Code (It is to make a batch of parsing dishes for the official answer and then re-implement it again ...)

/**
 * @Auther: wwh
 * @Date: 2020-03-12 22:55
 * @Description
 */

class BuildTree {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || preorder.length == 0) {
            return null;
        }
        //把中序的节点放在map里 妙啊
        Map<Integer, Integer> indexMap = new HashMap<Integer, Integer>();
        int length = preorder.length;
        for (int i = 0; i < length; i++) {
            indexMap.put(inorder[i], i);
        }
        TreeNode root = buildTree(preorder, 0, length - 1, inorder, 0, length - 1, indexMap);
        return root;
    }

    public TreeNode buildTree(int[] preorder, int preorderStart, int preorderEnd, int[] inorder, int inorderStart, int inorderEnd, Map<Integer, Integer> indexMap) {
        if (preorderStart > preorderEnd) {
            return null;
        }
        int rootVal = preorder[preorderStart];
        TreeNode root = new TreeNode(rootVal);
        if (preorderStart == preorderEnd) {
            return root;
        } else {
            int rootIndex = indexMap.get(rootVal);
            //左边叶子节点的个数
            int leftNodeSize = rootIndex - inorderStart;
            //右边叶子节点的个数
            int rightNodeSize = inorderEnd - rootIndex;
            TreeNode leftSubtree = buildTree(preorder, preorderStart + 1, preorderStart + leftNodeSize, inorder, inorderStart, rootIndex - 1, indexMap);
            TreeNode rightSubtree = buildTree(preorder, preorderEnd - rightNodeSize + 1, preorderEnd, inorder, rootIndex + 1, inorderEnd, indexMap);
            root.left = leftSubtree;
            root.right = rightSubtree;
            return root;
        }
    }
Published 33 original articles · praised 37 · 110,000 views

Guess you like

Origin blog.csdn.net/hagle_wang/article/details/104831197