剑指offer:重建二叉树的C++实现

剑指offer:重建二叉树的C++实现_第1张图片

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

TreeNode* built(vector<int>& preorder,vector<int>& inorder)
{
	if(preorder.size()==0 || inorder.size()==0 || preorder.size()!=inorder.size()) return NULL;
	return build(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
}

TreeNode* build(vector<int>& preorder,int left1,int right1,vector<int>& inorder,int left2,int right2)
{
	//建立根节点
	TreeNode* root=new TreeNode(preorder[left1]);
	int i=left2;
	while(preorder[left1]!=inorder[i]) i++;
	int left_len=i-left2;//左子树长度
	int right_len=right2-i;//右子树长度
	if(left_len>0) root->left=build(preorder,left1+1,left1+left_len,inorder,left2,i-1);
	if(right_len>0) root->right=build(preorder,left1+left_len+1,right1,inorder,i+1,right2);
	return root;
}

你可能感兴趣的:(c++算法代码)