Construct Binary Tree from Preorder and Inorder Traversal [LeetCode]

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

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

Solution: Just do it recursively.

 1     TreeNode *build(vector<int> &preorder, int pstart, int pend, vector<int> &inorder, int istart, int iend) {

 2         TreeNode * root = new TreeNode(preorder[pstart]); 

 3         int idx_root = -1;

 4         for(int i = istart; i <= iend; i ++) {

 5             if(inorder[i] == preorder[pstart]){

 6                 idx_root = i;

 7                 break;

 8             }

 9         }

10         

11         if(idx_root == -1)

12             return NULL;

13             

14         int left_size = idx_root - istart;

15         if(left_size > 0 )

16             root->left = build(preorder, pstart + 1, pstart + left_size, inorder, istart, idx_root - 1);

17             

18         int right_size = iend - idx_root;

19         if(right_size > 0)

20             root->right = build(preorder, pend - right_size + 1 , pend, inorder, idx_root + 1, iend);

21         

22         return root;

23     }

24 

25     TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {

26         if(preorder.size() == 0 || inorder.size() == 0 || preorder.size() != inorder.size())

27             return NULL;

28         

29         return build(preorder, 0, preorder.size() -1, inorder, 0, inorder.size() - 1);

30     }

 

你可能感兴趣的:(LeetCode)