Reconstruct binary tree based on preorder traversal and inorder traversal results

The idea is very simple, just use the idea of ​​divide and conquer. The core is to find out the array where the left and right subtrees are located.

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:

    TreeNode* reConstructBinaryTree(vector<int> pre, int preStart, int preEnd, vector<int> vin, int vinStart, int vinEnd) {
    	if (preStart> preEnd || vinStart> vinEnd)
    	{
    		return NULL;
    	}

    	int value = pre[preStart];
    	TreeNode *root = new TreeNode(value);
    	for (int i = vinStart; i <= vinEnd; ++i)
    	{
    		if (value == vin[i])
    		{
    			int leftTreeSize = i - vinStart;
    			root->left = reConstructBinaryTree(pre, preStart+1, preStart + leftTreeSize, vin, vinStart, i - 1);
    			root->right = reConstructBinaryTree(pre, preStart + leftTreeSize + 1, preEnd, vin, i + 1, vinEnd);
    		}
    	}
    	return root;
    }

    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {

    	int preSize = pre.size();
    	int vinSize = vin.size();
    	if (preSize == 0 || preSize! = vinSize)
    	{
    		return NULL;
    	}
    	return reConstructBinaryTree(pre, 0, preSize - 1, vin, 0, vinSize - 1);
    }
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325124777&siteId=291194637