剑指offer面试题6:重建二叉树

来源:互联网 发布:百度云盘 linux客户端 编辑:程序博客网 时间:2024/06/11 15:20
#include "iostream"#include <string>#include "stack"using namespace std;struct BinaryTreeNode{int data;BinaryTreeNode *left;BinaryTreeNode *right;};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->data = rootValue;root->left = root->right = NULL;if (startPreorder==endPreorder){if (startInorder == endInorder&&*startInorder == *startPreorder)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){//leftroot->left = constructCore(startPreorder + 1, leftPreorderEnd, startInorder, rootInorder - 1);}if (leftLength < endPreorder - startPreorder){//rightroot->right = constructCore(leftPreorderEnd + 1, endPreorder, rootInorder + 1, endInorder);}return root;}int main(){system("pause");return 0;}

0 0
原创粉丝点击