根据前序遍历和中序遍历结果重构二叉树

思路很简单,只是用到分治法思想。核心是找出左右子树所在的数组。

/**
 * 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);
    }
};

猜你喜欢

转载自www.cnblogs.com/ccXgc/p/8978541.html