LeetCode-105:Construct Binary Tree from Preorder and Inorder Traversal (利用先序和中序遍历构建二叉树) -- medium

Question

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:

  • You may assume that duplicates do not exist in the tree.

问题解析:

给定一棵树的先序和中序遍历数组,构建该二叉树。

Answer

Solution 1:

数据结构,递归调用。

与LeetCode-106:Construct Binary Tree from Inorder and Postorder Traversal的思想是相同的。

  • 利用先序遍历的最先的一个元素为子树的根结点,该根结点在中序遍历的位置为左右子树的分割点。
  • 需要注意左右子树的边界。
/**
 * 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[] preorder, int[] inorder) {
        if (preorder == null || inorder == null || preorder.length != inorder.length) return null;
        Map inMap = new HashMap();
        for(int i = 0; i < inorder.length; i++) {
            inMap.put(inorder[i], i);
        }

        TreeNode root = buildTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1, inMap);
        return root;
    }

    public TreeNode buildTree(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd, Map inMap) {
        if(preStart > preEnd || inStart > inEnd) return null;

        TreeNode root = new TreeNode(preorder[preStart]);
        int inRoot = inMap.get(root.val);
        int numsLeft = inRoot - inStart;

        root.left = buildTree(preorder, preStart + 1, preStart + numsLeft, inorder, inStart, inRoot - 1, inMap);
        root.right = buildTree(preorder, preStart + numsLeft + 1, preEnd, inorder, inRoot + 1, inEnd, inMap);

        return root;
    }
}
  • 时间复杂度:O(lgn),空间复杂度:O(n)

Solution 2:

python 解法,更加简洁。

  • 以preorder从前到后一直保存的是子树的根结点,所以取根结点直接pop(0),先建立左子树,再建立右子树。
  • 更加清晰简洁。
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def buildTree(self, preorder, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: TreeNode
        """
        if not preorder or not inorder:
            return None

        root = TreeNode(preorder.pop(0))
        preorderindex = inorder.index(root.val)

        root.left = self.buildTree(preorder, inorder[:preorderindex])
        root.right = self.buildTree(preorder, inorder[preorderindex+1:])

        return root

你可能感兴趣的:(LeetCode刷题,LeetCode,刷题)