构建二叉树
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
限制:
0 <= 节点个数 <= 5000
解法:采用递归的形式,在前序遍历中找父节点,然后根据父节点在中序遍历中找到左子树和右子树的结点个数。进行递归构造。
遇到的问题:在创建结点的时候对结构体指针的初始化问题没有弄明白(声明一个结构体指针记得初始化,一定要初始化,不初始化会出事)
TreeNode* root = new TreeNode(rootValue);
root->value = 3;
不能在没有初始换的情况下使用(错误):
TreeNode* root;
root->value = 3;
/**
* 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.empty() || inorder.empty()){
return nullptr;
}
int preStart = 0,preEnd = preorder.size()-1,inStart = 0,inEnd = inorder.size() - 1;
return constructCore(preorder,preStart,preEnd,inorder,inStart,inEnd);
}
TreeNode* constructCore(vector<int>& preorder, int preStart, int preEnd, vector<int>& inorder, int inStart, int inEnd){
int rootValue = preorder[preStart];
TreeNode* root = new TreeNode(rootValue);
root->left = root->right = nullptr;
int rootInNode=inStart;
while ((rootInNode < inEnd) && (inorder[rootInNode]!=rootValue)){
rootInNode++;
};
int leftLength=0, rightLength=0;
leftLength = rootInNode -inStart;
rightLength = inEnd - rootInNode;
if(leftLength > 0)
root->left = constructCore(preorder,preStart+1,preStart+leftLength,inorder,inStart,rootInNode-1);
if(rightLength > 0){
root->right = constructCore(preorder,preStart+leftLength+1,preEnd,inorder,rootInNode+1,inEnd);
}
return root;
}
};