Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal
程序员文章站
2022-03-04 19:05:04
...
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
/**
* 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 current = inorder.size() - 1;
return build(postorder, inorder, current, 0, postorder.size() - 1);
}
private:
TreeNode* build(vector<int>& postorder, vector<int>& inorder, int& current, int start, int end) {
if(current == -1 || start > end) {
return nullptr;
}
int value = postorder[current];
TreeNode* node = new TreeNode(value);
int index = 0;
for(int i = start; i <= end; i++) {
if(inorder[i] == value) {
index = i;
break;
}
}
current--;
node->right = build(postorder, inorder, current, index + 1, end);
node->left = build(postorder, inorder, current, start, index - 1);
return node;
}
};
Reference
推荐阅读
-
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
-
leetcode: binary-tree-postorder-traversal:后序遍历二叉树
-
LeetCode 94. Binary Tree Inorder Traversal
-
LeetCode145. Binary Tree Postorder Traversal(后序遍历)