描述 Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. For example, given preorder = [3,9,20,15,7] inorder = [9,3,15,20,7] Return the following binary tree:
3
/ \
9 20
/ \
15 7
思路 给出前序与中序遍历结果,求解二叉树。可以观察前序遍历与中序遍历的规律,由前序遍历的性质可以推断出,前序遍历的第一个元素一定是根节点,在给出的例子中,3一定是根节点,这时候继续看中序遍历,在根节点前面的一定是左子树,在例子中,9一定是根节点的左子树,在根节点后面的一定是右子树,在例子中15、20、7一定是右子数。这样,可以递归调用,截取3前面的中序遍历继续作为中序遍历的集合,截取同样长度的前序集合同样作为前序遍历集合,这样递归生成的是左孩子,右孩子则是递归调用剩余的元素。详见下面代码。 代码(c#)
public TreeNode BuildTree(int [] preorder, int [] inorder) {
if (preorder.Length == 0 )
return null ;
if (preorder.Length == 1 )
return new TreeNode(preorder[0 ]);
TreeNode node = new TreeNode(preorder[0 ]);
int index = 0 ;
for (int i = 0 ; i < inorder.Length; i++)
{
if (inorder[i] == node.val)
{
index = i;
break ;
}
}
node.left = BuildTree(preorder.Skip(1 ).Take(index ).ToArray(), inorder.Take(index ).ToArray());
node.right = BuildTree(preorder.Skip(index +1 ).ToArray(), inorder.Skip(index +1 ).ToArray());
return node;
}