从中序与后序遍历序列构造二叉树
- 题目描述
- 算法分析
- 编程代码
链接: 从中序与后序遍历序列构造二叉树
题目描述
算法分析
编程代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* _bulid(vector<int>& inorder, vector<int>& postorder,
int postbegin,int& orderi,int postend)
{
if(postbegin > postend)
{
return nullptr;
}
TreeNode* root = new TreeNode(postorder[orderi]);
//查找父节点
int rooti = postbegin;
while(rooti <= postend && rooti >= 0)
{
if(postorder[orderi] == inorder[rooti])
{
--orderi;
break;
}
++rooti;
}
root->right = _bulid(inorder,postorder,rooti+1,orderi,postend);
root->left = _bulid(inorder,postorder,postbegin,orderi,rooti-1);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
int i = postorder.size()-1;
TreeNode* root = _bulid(inorder,postorder,0,i,inorder.size()-1);
return root;
}
};