构建二叉树
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
限制:
0 <= 节点个数 <= 5000
解法: 采用递归的形式,对从中序遍历中找父节点,然后根据父节点在前序遍历中找到左子树和右子树的结点。
遇到的问题: 在创建结点的时候对结构体指针的初始化问题没有弄明白(声明一个结构体指针记得初始化,一定要初始化,不初始化会出事)
在获取父节点在中序遍历中的位置后,不能直接用来指定先序遍历中结点的位置,要借助length来计算。
TreeNode* root = new TreeNode(rootValue);
root->value = 3;
不能在没有初始换的情况下使用(错误):
TreeNode* root;
root->value = 3;
Solution:
/**
* 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;
}
};
来源:CSDN
作者:li123_123_
链接:https://blog.csdn.net/li123_123_/article/details/104341805