Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- knakul853
- */
- class Solution {
- public:
- TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder)
- {
- int n = (int)preorder.size();
- int m = (int)preorder.size();
- return dfs(preorder, 0, n-1, inorder, 0, m-1 );
- }
- TreeNode* dfs( vector<int>&pre, int pl,int pr, vector<int>&in, int il, int ir )
- {
- if( pl > pl || il > ir )
- return NULL;
- TreeNode* root = new TreeNode(pre[pl]);
- int id = -1;
- for(int i=il; i<=ir; i++)
- {
- if(in[i] == pre[pl])
- {
- id = i;
- break;
- }
- }
- if(id != -1)
- {
- root->left = dfs(pre, pl + 1, pr, in, il, id-1);
- root->right = dfs(pre, pl + id - il + 1, pr, in, id + 1, ir);
- }
- return root;
- }
- };
Add Comment
Please, Sign In to add comment