输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
简要题解:
我们可以根据前序遍历和中序遍历的特点判断出每个节点的左子树和右子树
然后递归解决。主要代码如下:
/**
* 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()!=inorder.size()||preorder.size()==0)return NULL;
vector<int>pre_left,pre_right,in_left,in_right;
int i=0;
for(i=0;i<inorder.size();i++)
{
if(preorder[0]==inorder[i])
break;
pre_left.push_back(preorder[i+1]);//前序遍历左子树
in_left.push_back(inorder[i]);//中序遍历左子树
}
for(int j=i+1;j<preorder.size();j++)
{
pre_right.push_back(preorder[j]);
in_right.push_back(inorder[j]);
}
TreeNode* rt=new TreeNode(preorder[0]);
rt->left=buildTree(pre_left,in_left);
rt->right=buildTree(pre_right,in_right);
return rt;
}
};