105. 先序、中序构造树



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

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

 

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:

        def build(preorder,inorder,pre_left,pre_right,in_left,in_right):
            if pre_right > len(preorder) or in_right > len(preorder):
                return None
            if in_left > in_right or pre_left > pre_right:
                return None
            val = preorder[pre_left]
            node = TreeNode(val)
            hd_index = inorder.index(val)
            left_cnt = hd_index - in_left
            right_cnt = in_right - hd_index
            node.left = build(preorder,inorder,pre_left+1,pre_left+left_cnt,in_left,in_left+left_cnt-1)
            node.right = build(preorder,inorder,pre_left+left_cnt+1,pre_right,in_left+left_cnt+1,in_right)
            return node
        n = len(preorder)
        return build(preorder,inorder,0,n-1,0,n-1)

 

 

 

class Solution {
private:
    unordered_map<int,int> index_map;
public:
    TreeNode* build(int pre_left,int pre_right, vector<int>& preorder, int in_left, int in_right,vector<int>& inorder) {
        if(pre_left > pre_right || in_left > in_right) return nullptr; 
        int inorder_index = index_map[preorder[pre_left]];
        int left_length = inorder_index  - in_left;
        TreeNode* root = new TreeNode(preorder[pre_left]);
        root->left = build(pre_left+1,pre_left+left_length,preorder,in_left,inorder_index-1,inorder);
        root->right= build(pre_left+left_length+1,pre_right,preorder,inorder_index+1,in_right,inorder);
        return root;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        for(int i = 0; i < inorder.size(); ++i) {
            index_map[inorder[i]] = i;
        }
        return build(0,preorder.size()-1,preorder,0,inorder.size()-1,inorder);
    }
};

 

 

 

 

 1 class Solution {
 2     public TreeNode buildTree(int[] preorder, int[] inorder) {
 3         return help(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
 4     }
 5     private TreeNode help(int[] preorder,int pre_start,int pre_end,int[] inorder,int in_start,int in_end){
 6         if(in_start>in_end || pre_start>pre_end) return null;
 7         
 8         
 9         TreeNode root = new TreeNode(preorder[pre_start]);
10         int j = in_start;
11         while(preorder[pre_start]!=inorder[j]&& j <=pre_end)
12             j++;
13         //注意下标!!!!!!!!
14         root.left = help(preorder,pre_start+1,pre_start+(j-in_start),inorder,in_start,j-1);
15         root.right = help(preorder,pre_start+(j-in_start)+1,pre_end,inorder,j+1,in_end);
16         return root;
17     }
18 }

 

posted @ 2018-01-26 16:35  乐乐章  阅读(179)  评论(0编辑  收藏  举报