LeetCode - Construct Binary Tree from Inorder and Postorder Traversal

Construct Binary Tree from Inorder and Postorder Traversal

2014.1.8 01:16

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

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

Solution:

  inorder traversal = left, root, right;

  postorder traversal = left, right, root;

  Thus the last element in the postorder sequence is the root. Find it in the inorder sequence and you know where the left and right subtrees are. Do this procedure recursively and the job is done.

  Time and space complexities are both O(n), where n is the number of nodes in the tree. The space complexity comes from the local parameters passed in function calls.

Accepted code:

 1 // 1CE, 1AC, good~

 2 /**

 3  * Definition for binary tree

 4  * struct TreeNode {

 5  *     int val;

 6  *     TreeNode *left;

 7  *     TreeNode *right;

 8  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}

 9  * };

10  */

11 class Solution {

12 public:

13     TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {

14         // IMPORTANT: Please reset any member data you declared, as

15         // the same Solution instance will be reused for each test case.

16         return recoverTree(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1);

17     }

18 private:

19     TreeNode *recoverTree(vector<int> &inorder, vector<int> &postorder, int l1, int r1, int l2, int r2) {

20         if(l1 > r1){

21             return nullptr;

22         }

23         

24         if(l2 > r2){

25             return nullptr;

26         }

27         

28         TreeNode *root = new TreeNode(postorder[r2]);

29         int i;

30         

31         for(i = l1; i <= r1; ++i){

32             if(inorder[i] == root->val){

33                 break;

34             }

35         }

36         

37         root->left = recoverTree(inorder, postorder, l1, i - 1, l2, l2 + (i - 1 - l1));

38         // 1CE here, , error

39         root->right = recoverTree(inorder, postorder, i + 1, r1, r2 - 1 - (r1 - i - 1), r2 - 1);

40         

41         return root;

42     }

43 };

 

你可能感兴趣的:(LeetCode)