标签:tree 节点 roo 时间 span nullptr 就是 没有 cut
思路就是从前序遍历出发,到中序遍历中找到相应的根节点,然后确定左子树和右子树的范围
struct BiNode { int value; BiNode *leftchild; BiNode *rightchild; }; class solution { public: BiNode* BiTree(int *preorder,int *midorder,int length) { if(length < 0 || preorder == nullptr || midorder == nullptr) return nullptr; return constructTree(preorder,preorder+length,midorder,midorder+length); } BiNode* constructTree(int* pre,int* pre_end,int* mid,int* mid_end) { int rootValue = pre[0]; BiNode* root = new BiNode(); root->value = rootValue; root->leftchild = nullptr; root->rightchild = nullptr; if(pre == pre_end) //×ó×ÓÊ÷½áÊø { if(mid == mid_end && mid == pre) return root; else throw std::exception("Invalid input.") } int* root_index = mid; while( root_index <=mid_end &&*root_index != rootValue) root_index++; int left_length = root_index - mid; int* left_end = pre + left_length; if(left_length > 0) { root->leftchild = constructTree(pre+1,pre_end,mid,root_index-1); root->rightchild = constructTree(pre+1,pre_end,root_index+1,mid_end); } return root; } };
最近开学,都没有什么时间继续学习这方面的东西了,o(╥﹏╥)o
标签:tree 节点 roo 时间 span nullptr 就是 没有 cut
原文地址:https://www.cnblogs.com/jianbo1995/p/9581644.html