2021-02-02 已知二叉树的前序遍历和中序遍历求二叉树

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

// 前序遍历二叉树左侧节点数 = 二叉树前序遍历头节点 +  二叉树的中序遍历左侧的节点数
// 注意: 
//你可以假设树中没有重复的元素。 
//
// 例如,给出 
//
// 前序遍历 preorder = [3,9,20,15,7]
//中序遍历 inorder = [9,3,15,20,7]
// 返回如下的二叉树: 
//
//     3
//   / \
//  9  20
//    /  \
//   15   7 
// Related Topics 树 深度优先搜索 数组
//  851  0


//leetcode submit region begin(Prohibit modification and deletion)

import java.util.HashMap;
import java.util.Map;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode() {}
 * TreeNode(int val) { this.val = val; }
 * TreeNode(int val, TreeNode left, TreeNode right) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
class Solution {
    private Map map = new HashMap();

    public TreeNode buildTree(int[] preorder, int[] inorder) {

        if (preorder.length != inorder.length) return null;
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }

        return buildTreeRun(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1);
    }

    private TreeNode buildTreeRun(int[] preorder, int[] inorder, int preStart, int preEnd, int inStart, int inEnd) {

        if (preStart>preEnd||inStart>inEnd)return null;

        int num = preorder[preStart];
        int mid = 0;
        mid = map.get(num);
        int leftLength = mid - inStart;

        TreeNode treeNode = new TreeNode(num);
        treeNode.left = buildTreeRun(preorder, inorder, preStart + 1, preStart + leftLength, inStart, mid - 1);

        treeNode.right = buildTreeRun(preorder, inorder, preStart + leftLength + 1, preEnd, mid + 1, inEnd);

        return treeNode;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

你可能感兴趣的:(算法,算法)