105. Construct Binary Tree from Preorder and Inorder Traversal
程序员文章站
2022-03-03 10:12:59
...
已知前序序列和中序序列,构建二叉树。
解法:递归
TreeNode *build(vector<int>& preorder, int preStart, int preEnd,
vector<int> &inorder, int inStart, int inEnd)
{
if(preStart > preEnd || inStart > inEnd)
return NULL;
int i = inStart;
for(; i <= inEnd; ++i)
{
if(preorder[preStart] == inorder[i])
break;
}
TreeNode *p = new TreeNode(preorder[preStart]);
int leftLen = i - inStart;
p->left = build(preorder, preStart + 1, preStart + leftLen, inorder, inStart, i-1);
p->right = build(preorder, preStart + 1 + leftLen, preEnd, inorder, i+1, inEnd);
return p;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return build(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
}
上一篇: 105. Construct Binary Tree from Preorder and Inorder Traversal
下一篇: 105. Construct Binary Tree from Preorder and Inorder Traversal
推荐阅读
-
LeetCode 105 Construct Binary Tree from Preorder and Inorder Traversal
-
LeetCode: 105. Construct Binary Tree from Preorder and Inorder Traversal
-
leetcode 随笔 Construct Binary Tree from Preorder and Inorder Traversal
-
105. Construct Binary Tree from Preorder and Inorder Traversal
-
Construct Binary Tree from Preorder and Inorder Traversal
-
Construct Binary Tree from Preorder and Inorder Traversal
-
LeetCode(106)Construct Binary Tree from Inorder and Postorder Traversal
-
105. Construct Binary Tree from Preorder and Inorder Traversal
-
LeetCode106. Construct Binary Tree from Inorder and Postorder Traversal
-
105. Construct Binary Tree from Preorder and Inorder Traversal