解法一:
/**
* 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>& preorder, vector<int>& inorder) {
if(preorder.size()==0)
return NULL; //空树
TreeNode* root = new TreeNode(preorder[0]);
if(preorder.size()==1)
return root; //只有一个节点
vector<int> leftIn,leftPre,rightIn,rightPre; //
int location = 0;
while(inorder[location]!=root->val) //在中序序列中找到根节点
{
leftIn.push_back(inorder[location]); //把中序遍历到根节点的值给中序左子树
location++;
}
for(int i=1;i<=location;i++) //把前序遍历到根节点的值给前序左子树
leftPre.push_back(preorder[i]);
for(int i=location+1;i<preorder.size();i++) //根节点右面的值是中序右子树
{
rightPre.push_back(preorder[i]); //把前序遍历到根节点的值给前序右子树
rightIn.push_back(inorder[i]); //把中序遍历到根节点的值给前序右子树
}
root->left = buildChild(leftPre,leftIn); //递归左子树
root->right = buildChild(rightPre,rightIn); //递归右子树
return root;
}
TreeNode* buildChild(vector<int> preorder,vector<int> inorder){
if(preorder.size()==0)
return NULL; //出口条件:preorder为空,则表示这个节点是NULL
TreeNode* root = new TreeNode(preorder[0]); //生成当前子树的根节点
vector<int> leftIn,leftPre,rightIn,rightPre;
int location = 0;
while(inorder[location]!=root->val)
{
leftIn.push_back(inorder[location]);
location++;
}
for(int i=1;i<=location;i++)
leftPre.push_back(preorder[i]);
for(int i=location+1;i<preorder.size();i++)
{
rightPre.push_back(preorder[i]);
rightIn.push_back(inorder[i]);
}
root->left = buildChild(leftPre,leftIn);
root->right = buildChild(rightPre,rightIn);
return root;
}
};
本文详细介绍了如何使用前序遍历和中序遍历序列构建二叉树的算法过程,通过递归的方式确定每个节点的位置,最终还原整个二叉树结构。
1113

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



