二叉树 在计算机科学中,二叉树(英语:Binary tree)是每个节点最多只有两个分支(即不存在分支度大于2的节点)的树结构[1]。通常分支被称作“左子树”或“右子树”。二叉树的分支具有左右次序,不能随意颠倒
二叉树深度 https://www.luogu.com.cn/problem/P4913
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 #include <bits/stdc++.h> #define int long long using namespace std;const int N = 1e6 + 10 ;struct node { int l, r; } tree[N]; int n, ans;void dfs (int id, int deep) { if (id == 0 ) return ; ans = max (ans, deep); dfs (tree[id].l, deep + 1 ); dfs (tree[id].r, deep + 1 ); } void solve () { cin >> n; for (int i = 1 ; i <= n; i++) cin >> tree[i].l >> tree[i].r; dfs (1 , 1 ); cout << ans << endl; } signed main () { ios::sync_with_stdio (0 ); cin.tie (0 ); cout.tie (0 ); int t = 1 ; while (t--) { solve (); } return 0 ; }
求先序排列 https://www.luogu.com.cn/problem/solution/P1030
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 #include <bits/stdc++.h> #define int long long using namespace std;string preorder; void dfs (string inorder, string postorder) { if (inorder.size () == 0 ) return ; char ch = postorder.back (); preorder += ch; int pos = inorder.find (ch); dfs (inorder.substr (0 , pos), postorder.substr (0 , pos)); dfs (inorder.substr (pos + 1 ), postorder.substr (pos, inorder.size () - pos - 1 )); } void solve () { string inorder, postorder; cin >> inorder >> postorder; dfs (inorder, postorder); cout << preorder << endl; } signed main () { ios::sync_with_stdio (0 ); cin.tie (0 ); cout.tie (0 ); int t = 1 ; while (t--) { solve (); } return 0 ; }