层序中序还原二叉树
原创 于 2023-10-19 11:36:44 发布 · 粉丝可见 · 200 阅读 · 0 · 0 · 本内容遵循CC 4.0 BY-SA版权协议 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 GEO检测 · 编辑
文章链接:https://blog.csdn.net/hacker_51/article/details/133921072
题目:

样例:
cobol<br/>6<br/>0 2 5 1 4 3<br/>1 2 4 0 5 3<br/> |

思路:
这道题,核心思想就是 结合 层序遍历的性质,根据 中序来判断左右孩子是否存在。
前中后序的遍历实现,主要都是递归的形式实现遍历
而层序遍历是 按照BFS的形式迭代遍历 ,以一层一层的搜的。
所以我们建树的时候结合 BFS 的层序规则建树
层序遍历数组中,第一个元素一定是根节点,随后不断的结合 中序数组判断左右子树
代码详解如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| #include <iostream> #include <vector> #include <queue> #include <cstring> #include <algorithm> #include <unordered_map> #define endl '\n' #define YES puts("YES") #define NO puts("NO") #define umap unordered_map #define All(x) x.begin(),x.end() #pragma GCC optimize(3,"Ofast","inline") #define IOS std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0) using namespace std; const int N = 2e6 + 10;
struct Node { int val; Node*lchild; Node*rchild; inline Node():val(-1),lchild(NULL),rchild(NULL){}; inline Node(int x):val(x),lchild(NULL),rchild(NULL){}; }*q[N]; int n; umap<int,int>inorder,lorder; umap<int,bool>st;
inline void biuldTree() { for(int i = 0,j = 1;j < n;) { for(int end = j;i < n;++i) { int p = inorder[lorder[i]]; st[p] = true; if(p && !st[p - 1]) { q[i]->lchild = new Node(lorder[j]); q[j++] = q[i]->lchild; } if(p + 1 < n && !st[p + 1]) { q[i]->rchild = new Node(lorder[j]); q[j++] = q[i]->rchild; } } } }
void preorder(Node* root) { if(root == NULL) return ; cout << root->val; if(--n) cout << ' '; preorder(root->lchild); preorder(root->rchild); } inline void solve() { cin >> n; for(int i = 0;i < n;++i) { cin >> lorder[i]; } for(int i = 0,x;i < n;++i) { cin >> x; inorder[x] = i; } q[0] = new Node(lorder[0]); biuldTree(); preorder(q[0]); } int main() {
IOS; int _t = 1;
while (_t--) { solve(); } return 0; }
|
最后提交:
