Given inorder and postorder traversal of a tree, construct the binary tree.
递归实现
/**
* 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 num = inorder.size();
if(num == 0)
return NULL;
return Recursion(0, num-1, num-1, inorder, postorder );
}
TreeNode* Recursion(int Istart,int Iend,int Pend,vector<int>& inorder, vector<int>& postorder){
if(Istart>Iend)
return NULL;
TreeNode* root = new TreeNode(postorder[Pend]); //标记根的位置,特别注意根位置的变化
int mid = 0;
for(int i=Istart; i<=Iend; ++i){
if(inorder[i]==root->val)
mid = i;
}
root->left = Recursion(Istart,mid-1,Pend-1-(Iend-mid),inorder, postorder); //递归指向左右的根
root->right = Recursion(mid+1,Iend,Pend-1,inorder,postorder);
return root;
}
};
本文介绍了一种通过中序和后序遍历构建二叉树的方法。利用递归方式确定每个节点的位置,最终构造完整的二叉树结构。

被折叠的 条评论
为什么被折叠?



