leetcode #105 in cpp

来源:互联网 发布:北京文森特软件科技 编辑:程序博客网 时间:2024/05/22 06:48

Solution:

The following example is from Wikipedia:


Pre-order: F, B, A, D, C, E, G, I, H.


In-order: A, B, C, D, E, F, G, H, I.


If we look at the lists given by pre-order and in-order traversals, we could see that:

1. root is always the first element in preorder list. 

2. In in-order list, the elements at the left of the root are always in the left subtree of the root, and the elements at the right of the root are always in the right subtree of the root. 

Say F is the first element in preorder, and thus F is the root. 

In inorder, A,B,C,D,E are at left of F, and all of them are in the left subtree in the graph, while G,H,I are at right of F and thus all of them are in the right subtree. 


So:

1. we find current root, r,  in preorder

2. we find r in inorder. 

3. we partition preorder and inorder into two parts, one of which is for left subtree and the other is for the right subtree. 

4. we use the same method to construct the left subtree and right subtree given that we have the corresponding preorder and inorder for both of them. 

Code:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {        return build(0, preorder.size() - 1, 0, inorder.size() - 1, preorder, inorder);    }    TreeNode *build(int pre_start, int pre_end, int in_start, int in_end, vector<int>& preorder, vector<int>& inorder){        if(pre_start > pre_end || in_start > in_end) return NULL;                 //current root in the first number in preorder        TreeNode *root = new TreeNode(preorder[pre_start]);                //find root in inorder        int in_root = -1;        for(int i = in_start; i <= in_end; i ++){            if(root->val == inorder[i]){                in_root = i;                 break;//locate root in inorder            }        }                //paritition preorder and inorder into left subtree and right subtree        TreeNode *left = NULL;        TreeNode *right = NULL;                 int leftcount = in_root - in_start; //from instart to inroot - 1, these numbers are in left substree        left = build(pre_start+1, pre_start + leftcount, in_start, in_root - 1, preorder, inorder);         right = build(pre_start + leftcount + 1, pre_end , in_root+1, in_end, preorder,inorder);                 root->left = left;         root->right = right;         return root;     }};

0 0
原创粉丝点击