树的操作(完)
/* ------------------------------------------------- Author: wry date: 2022/2/24 11:22 Description: Tree ------------------------------------------------- */ #include <bits/stdc++.h> using namespace std; struct TreeNode { char data; TreeNode *left; TreeNode *right; TreeNode(char d):data(d),left(nullptr),right(nullptr) {} }; //二叉排序树的插入值 TreeNode* Insert(TreeNode *root,char d) { if (root == nullptr) { root = new TreeNode(d); } else { if (d < root->data) { root->left = Insert(root->left,d); } else if (d > root->data){ root->right = Insert(root->right,d); } } return root; } //先序排序 void PreOrder (TreeNode* root) { if (root == nullptr) { return ; } printf ("%c ",root->data); PreOrder(root->left); PreOrder(root->right); return ; } //中序排序 void InOrder (TreeNode* root) { if (root == nullptr) { return ; } InOrder(root->left); printf ("%c ",root->data); InOrder(root->right); return ; } //后序排序 void PostOrder (TreeNode* root) { if (root == nullptr) { return ; } PostOrder(root->left); PostOrder(root->right); printf ("%c ",root->data); return ; } //层序遍历 void LevelOrder(TreeNode* root) { if (root==nullptr) { return ; } tree.push(root); while (tree.size()!=0) { cout << tree.front()->data << " "; if (tree.front()->lchild!= nullptr) { tree.push(tree.front()->lchild); } if (tree.front()->rchild!= nullptr) { tree.push(tree.front()->rchild); } tree.pop(); } return ; } //通过先序+中序序列(字符串),构造树 TreeNode* PreAndInBuild (string preorder,string inorder) { if (preorder.size() == 0) { return nullptr; } char c = preorder[0]; TreeNode* root = new TreeNode(c); //为此值创建一个结点 int position = inorder.find(c); //找到c在inorder出现的位置(下标值) root->left = PreAndInBuild(preorder.substr(1,position),inorder.substr(0,position)); root->right = PreAndInBuild(preorder.substr(position+1),inorder.substr(position+1)); //表示从下标positio+1开始到结尾 return root; } //后序+中序 TreeNode* PostAndInBuild (string postorder,string inorder) { if (postorder.size()==0) { return nullptr; } char c = postorder[postorder.size()-1]; TreeNode* root = new TreeNode(c); int position = inorder.find(c); root->left = PostAndInBuild(postorder.substr(0,position),inorder.substr(0,position)); root->right = PostAndInBuild(postorder.substr(position,inorder.size()-position-1),inorder.substr(position+1)); return root; } int main() { string levelorder = "ABCDE"; string inorder = "ACBED"; TreeNode* root = LevelAndInBuild(levelorder,inorder); PreOrder(root); return 0; }
二叉树的构造、三种遍历、根据遍历构建二叉树、二叉排序树的插入生成......
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术