二叉树结点定义
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
二叉树的构造
层序序列构造
- 输入完全二叉树的序列,空结点位置用特殊字符标记,输出构造好的二叉树。
- 基于队列 + bfs即可。
前序序列和中序序列构造
TreeNode* build(vector<int>& preorder, int preStart, int preEnd, vector<int>& inorder, int inStart, int inEnd){
if(preStart > preEnd || inStart > inEnd) return nullptr;
int rootVal = preorder[preStart];
int index = 0;
for(int i = inStart; i <= inEnd; i++){
if(inorder[i] == rootVal){
index = i;
break;
}
}
int leftSize = index - inStart;
TreeNode *root = new TreeNode(rootVal);
root->left = build(preorder, preStart + 1,preStart + leftSize, inorder, inStart, index - 1);
root->right = build(preorder, preStart + leftSize + 1, preEnd, inorder, index + 1, inEnd);
return root;
}
后序序列和中序序列构造
TreeNode *build(vector<int>& inorder,int inStart,int inEnd, vector<int>& postorder,int postStart,int postEnd){
if(inStart>inEnd || postStart>postEnd)
return nullptr;
int rootVal = postorder[postEnd];
int index = 0;
for(int i = inStart;i <= inEnd;i++){
if(inorder[i] == rootVal)
index = i;
}
int leftSize = index - inStart;
TreeNode *root = new TreeNode(rootVal);
root->left = build(inorder,inStart,index - 1,postorder,postStart,postStart + leftSize -1);
root->right = build(inorder,index + 1,inEnd,postorder,postStart + leftSize,postEnd - 1);
return root;
}
序列化和反序列化
层序序列化和反序列化
前序序列化和反序列化