Construct Binary Tree from Preorder and Inorder Traversal

brucehb發表於2017-01-31

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

Note:

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

struct Node
{
	int val;
	Node(int v)
	{
		val = v;
		left = right = NULL;
	}
	Node *left;
	Node *right;
};

Node* visit(vector<int> &preorder, int preLeft, int preRight, vector<int> &inorder, int inLeft, int inRight)
{
	if (preLeft > preRight)
	{
		return NULL;
	}
	
	int index = inLeft;
	for (;index <= inRight; index++)
	{
		if (inorder[index] == preorder[preLeft])
		{
			break;
		}
	}
	
	int leftLength = index - inLeft;
	Node *left = visit(preorder, preLeft+1, preLeft+leftLength, inorder, inLeft, index-1);
	Node *right = visit(preorder, preLeft+leftLength+1, preRight, inorder, index+1, inRight);
	
	Node *p = new Node(preorder[preLeft]);
	p->left = left;
	p->right = right;
	
	return p;
}
Node* buildTree(vector<int> &preorder, vector<int> &inorder)
{
	if (preorder.size() < 1)
	{
		return NULL;
	}
	
	return visit(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
}


相關文章