2 Star 0 Fork 0

xinanXu/myleetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
LC105.cpp 1.23 KB
一键复制 编辑 原始数据 按行查看 历史
xinanXu 提交于 2023-02-10 17:56 . 105 先序和后序创建二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildSubTree(vector<int>& preorder, int pleft, int pright, vector<int>& inorder, int ileft, int iright) {
if (pleft >= preorder.size() || ileft >= inorder.size()) return nullptr;
if (pright < 0 || iright < 0) return nullptr;
if (pright < pleft || iright < ileft) return nullptr;
if (pleft == pright) return new TreeNode(preorder[pleft]);
TreeNode* ret = new TreeNode;
ret->val = preorder[pleft];
int len = pright - pleft;
for (int i = 0; i <= len; i++) {
if (preorder[pleft] == inorder[i+ileft]) {
ret->left = buildSubTree(preorder, pleft+1, pleft+i, inorder, ileft, ileft+i-1);
ret->right = buildSubTree(preorder, pleft+1+i, pright, inorder, ileft+i+1, iright);
}
}
return ret;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return buildSubTree(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
}
};
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/DearAtri/myleetcode.git
git@gitee.com:DearAtri/myleetcode.git
DearAtri
myleetcode
myleetcode
master

搜索帮助