剑指offer-面试题6

来源:互联网 发布:数组怎么输出 编辑:程序博客网 时间:2024/06/07 14:46

题目: 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。

解题思路:递归实现

/*********************** 面试题6 : 重建二叉树***********************/struct BinaryTreeNode{intValue;BinaryTreeNode*pLeft;BinaryTreeNode*pRight; };BinaryTreeNode* Construct(int* preorder, int* inorder, int length){if(preorder == NULL || inorder == NULL || length <= 0)return NULL;return ConstructCore(preorder, preorder + length - 1,inorder, inorder + length - 1);}BinaryTreeNode* ConstructCore(int* startPreorder, int* endPreorder,int* startInorder, int* endInorder){//前序遍历序列的第一个数字是根节点的值int rootValue = startPreorder[0];BinaryTreeNode* root = new BinaryTreeNode();root->Value = rootValue;root->pLeft = root->pRight = NULL;if(startPreorder == endPreorder){if(startInorder = endInorder && *startPreorder == *startInorder) return root;elsethrow exception("Invalid input");}// 在中序遍历序列中找到根节点的值int* rootInorder = startInorder;while(rootInorder <= endInorder && *rootInorder != rootValue){++rootInorder;}if(rootInorder == endInorder && *rootInorder != rootValue){throw exception("Invalid input");}int leftLength = rootInorder - startInorder;int* leftPreorderEnd  = startPreorder +leftLength;if(leftLength > 0){//构建左子树root->pLeft = ConstructCore(startPreoder + 1, leftPreorderEnd, startInorder, rootInorder -1);}if(leftLength < endPreorder - startPreorder){//构建右子树root->pRight = ConstructCore(leftPreorderEnd + 1,endPreorder, rootInorder + 1, endInorder);}return root;}


0 0
原创粉丝点击