LeetCode 106. 从中序与后序遍历序列构造二叉树(二叉树基础之树的重建)
程序员文章站
2022-05-20 20:25:12
...
/**
* 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 n = inorder.size();
return create(0,n-1,0,n-1,inorder,postorder);
}
TreeNode* create(int postL,int postR,int inL,int inR,vector<int>& inorder, vector<int>& postorder){
if(postL>postR){
return nullptr;
}
TreeNode* root = new TreeNode(postorder[postR]);
int idx = 0;
for(int i = inL;i<=inR;i++){
if(inorder[i]==postorder[postR]){
idx = i;
break;
}
}
int numLeft = idx-inL;
root->left = create(postL,postL+numLeft-1,inL,idx-1,inorder,postorder);
root->right = create(postL+numLeft,postR-1,idx+1,inR,inorder,postorder);
return root;
}
};
上一篇: LeetCode 1361. 验证二叉树(几种错误、递归建树)
下一篇: B:Butterfly