C++详解Leetcode:106. Construct Binary Tree from Inorder and Postorder Traversal
程序员文章站
2022-03-07 23:49:25
...
原题
思路
通过二叉树的中序遍历和后序遍历来构建二叉树,通过递归可以很简单的解决
code
/**
* 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* buildTree(vector<int>& inorder, vector<int>& postorder) {
int l1 = 0;
int l2 = 0;
int r1 = inorder.size() - 1;
int r2 = postorder.size() - 1;
TreeNode *s = (TreeNode*)malloc(sizeof(TreeNode));
//s = NULL;
s = CreateBT(inorder, postorder, l1, r1, l2, r2);
return s;
}
TreeNode* CreateBT(vector<int>& inorder, vector<int>& postorder, int l1, int r1, int l2, int r2)
{
TreeNode* s;
int i;
if (l1 > r1)
return NULL;
s = (TreeNode*)malloc(sizeof(TreeNode));
s->left = s->right = NULL;
for (i = l1; i <= r1; i++)
{
if (inorder[i] == postorder[r2])
{
break;
}
}
s->val = inorder[i];
s->left = CreateBT(inorder, postorder, l1, i - 1, l2, l2 + i -l1 - 1);
s->right = CreateBT(inorder, postorder, i + 1, r1, l2 + i - l1, r2 - 1);
return s;
}
};
推荐阅读
-
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
-
LeetCode(106)Construct Binary Tree from Inorder and Postorder Traversal
-
LeetCode106. Construct Binary Tree from Inorder and Postorder Traversal
-
LeetCode-----Construct Binary Tree from Preorder and Inorder Traversal
-
Construct Binary Tree from Inorder and Postorder Traversal
-
Construct Binary Tree from Inorder and Postorder Traversal
-
LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal
-
leetcode【105-106】Construct Binary Tree from Inorder and Preorder Traversal && Postorder Traveresal