Construct Binary Tree from Preorder and Inorder Traversal

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

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

代码:

 1     TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
 2         // IMPORTANT: Please reset any member data you declared, as
 3         // the same Solution instance will be reused for each test case.
 4         int len = preorder.size();
 5         if(len == 0)
 6             return NULL;
 7         TreeNode *root = new TreeNode(preorder[0]);
 8         int i;
 9         for(i = 0; i < len; i++){
10             if(inorder[i] == preorder[0])
11                 break;
12         }
13         vector<int> lpreorder(preorder.begin()+1, preorder.begin()+i+1);
14         vector<int> linorder(inorder.begin(), inorder.begin()+i);
15         vector<int> rpreorder(preorder.begin()+i+1, preorder.end());
16         vector<int> rinorder(inorder.begin()+i+1, inorder.end());
17         vector<int>().swap(preorder);
18         vector<int>().swap(inorder);
19         root->left = buildTree(lpreorder, linorder);
20         root->right = buildTree(rpreorder, rinorder);
21         return root;
22     }

 

posted on 2013-11-08 21:54  waruzhi  阅读(120)  评论(0编辑  收藏  举报

导航