当前位置:网站首页>105. constructing binary trees from preorder and inorder traversal sequences

105. constructing binary trees from preorder and inorder traversal sequences

2022-06-13 06:40:00 Mr Gao

105. Construction of binary trees from traversal sequences of preorder and middle order

Given two arrays of integers preorder and inorder , among preorder Is the prior traversal of a binary tree , inorder Is the middle order traversal of the same tree , Please construct a binary tree and return its root node .

Example 1:
 Insert picture description here

Input : preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output : [3,9,20,null,null,15,7]

Example 2:

Input : preorder = [-1], inorder = [-1]
Output : [-1]

The solution code is as follows :


 int  root_preorder(int *preorder,int left,int right){
    
     return preorder[left];
 }
 int find_root(int* inorder,int left,int right,int val){
    
     int i;
     for(i=left;i<=right;i++){
    
         if(inorder[i]==val){
    
             return i;
         }
     }
     return 0;
 } 
 int find_pre(int* preorder,int preleft,int preright,int* inorder,int inleft,int inright){
    
     int i;
     int j;
      for(i=preleft;i<=preright;i++){
    
         for(j=inleft;j<=inright;j++){
    
             if(preorder[i]==inorder[j]){
    
                 return i;
             }
         }
     }
return 0;

 }
 void create_tree_dfs(int* preorder,int preleft,int preright,int* inorder,int inleft,int inright,struct TreeNode **r){
    
     if(preleft<=preright){
    

         int val=root_preorder(preorder,preleft,preright);
           (*r)->val=val;
           (*r)->left=(struct TreeNode* )malloc(sizeof(struct TreeNode));
            (*r)->right=(struct TreeNode* )malloc(sizeof(struct TreeNode));
            int in_root_index=find_root(inorder,inleft,inright,val);
         
            int left_index=find_pre(preorder,preleft,preright,inorder,inleft,in_root_index-1);
           // printf("left_index %d |",left_index);
          create_tree_dfs(preorder,left_index,left_index+in_root_index-inleft-1,inorder,inleft,in_root_index-1,&((*r)->left));
            int right_index=find_pre(preorder,preleft,preright,inorder,in_root_index+1,inright);
           // printf("right_index %d |",right_index);
         create_tree_dfs(preorder,right_index,right_index+inright-in_root_index-1,inorder,in_root_index+1,inright,&((*r)->right));


     }
     else{
    
          *(r)=NULL;
     }
   


 }


struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize){
    
    struct TreeNode* r=(struct TreeNode* )malloc(sizeof(struct TreeNode));
  
  create_tree_dfs(preorder,0,preorderSize-1,inorder,0,inorderSize-1,&r);

    return r;

}
原网站

版权声明
本文为[Mr Gao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/164/202206130620210759.html