knakul853

Untitled

Jul 22nd, 2020
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. /**
  2. knakul853
  3.  */
  4. class Solution {
  5. public:
  6.     TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder)
  7.     {
  8.         int n = (int)preorder.size();
  9.         int m = (int)preorder.size();
  10.        
  11.        return dfs(preorder, 0, n-1, inorder, 0, m-1 );
  12.     }
  13.    
  14.     TreeNode* dfs( vector<int>&pre, int pl,int pr, vector<int>&in, int il, int ir )
  15.     {
  16.         if( pl > pl || il > ir )
  17.             return NULL;
  18.         TreeNode* root = new TreeNode(pre[pl]);
  19.        
  20.         int id = -1;
  21.         for(int i=il; i<=ir; i++)
  22.         {
  23.             if(in[i] == pre[pl])
  24.             {
  25.                 id = i;
  26.                 break;
  27.             }
  28.         }
  29.        
  30.         if(id != -1)
  31.         {
  32.            
  33.           root->left = dfs(pre, pl + 1, pr, in, il, id-1);
  34.            
  35.           root->right = dfs(pre, pl + id - il + 1, pr, in,  id + 1, ir);
  36.                          
  37.         }
  38.        
  39.         return root;
  40.        
  41.     }
  42. };
Add Comment
Please, Sign In to add comment