105. 从前序与中序遍历序列构造二叉树

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

注意:
你可以假设树中没有重复的元素。

例如,给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]

返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

py

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        if not preorder: return None #check if the tree is null
        root = TreeNode(preorder[0]) #get the root by preorder[0]
        
        i = inorder.index(root.val) #find the root index in the inorder, supposing preorder and inorder consist of unique values
        # DFS for root.left and root.right according to the structure of preorder and inorder
        root.left = self.buildTree(preorder[1:i+1], inorder[:i]) 
        root.right = self.buildTree(preorder[i+1:], inorder[i+1:])

        return root

 

Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public Map<Integer,Integer>map;

    public TreeNode mybuildTree(int[] preorder, int[] inorder,int preorder_left,int preorder_right,int inorder_left,int inorder_right) {
        if(preorder_left>preorder_right)return null;
        int preorder_root=preorder_left;
        int inorder_root=map.get(preorder[preorder_root]);
        TreeNode root=new TreeNode(preorder[preorder_root]);
        int size_left_subtree=inorder_root-inorder_left;
        root.left=mybuildTree(preorder,inorder,preorder_left+1,preorder_left+size_left_subtree,inorder_left,inorder_root-1);
        root.right=mybuildTree(preorder,inorder,preorder_left+size_left_subtree+1,preorder_right,inorder_root+1,inorder_right);
        return root;
    }
    
    public TreeNode buildTree(int[] preorder, int[] inorder){
        int n=preorder.length;
        map=new HashMap<Integer,Integer>();
        for(int i=0;i<n;i++){
            map.put(inorder[i],i);
        }
        return mybuildTree(preorder,inorder,0,n-1,0,n-1);
    }
}

 

posted @ 2020-12-24 16:48  XXXSANS  阅读(120)  评论(0编辑  收藏  举报