今天学了树、二叉树的遍历,以及AC的题
树的定义:
树是由n(n>=0)个结点所构成的有限集合
当n=0时,称为空树
当n>0时,n个结点满足以下条件
有且仅有一个称为根的结点其余结点可分为m个互不相交的有限集合,且每一个集合又构成一棵树,该树称为根节点的子树。
对于一颗非空树,其中有且仅有一个没有前驱的结点,这个结点就是根节点,其余结点有且仅有一个前驱,但可以有多个后继。
二叉树定义:
二叉树是一个特殊的树,每个结点最多只有两棵子树,且两棵子树也是二叉树。
精确定义:二叉树是由n(n>=0)个结点所构成的有限集合。当n=0时,这个集合为空,此时二叉树为空树,当n>0时,这个集合是由一个根结点和两个互不相交的分别称为左子树和右子树的二叉树构成。
二叉树的两棵子树有左右之分,所以二叉树是有序树。
二叉树的三种序列:
先序、中序、后序
先序(根左右)中序(左根右)后序(左右根)
//二叉树的三种遍历方式
node{
int data;
node* left;
node* right;
}tree,a,c;
void solve1(node * t) {// 先序
if (t != NULL) {
cout << t->data;
solve1(t->left);
solve1(t->right);
}
}
void solve2(node* t) { // 中序
if (t != NULL) {
solve2(t->left);
cout << t->data;
solve2(t->right);
}
}
void solve3(node* t) { // 后序
if (t != NULL) {
solve3(t->left);
solve3(t->right);
cout << t->data;
}
}
int main() {
tree.data = 1;
a.data = 2;
c.data = 3;
tree.left = &a;
tree.right = &c;
a.left = a.right = NULL;
c.left = c.right = NULL;
solve1(&tree);
return 0;
}
题目链接:美国血统
题解:STL大法好,利用先序找根,利用中序分出根左边和根右边部分
AC代码:
#include <iostream>
#include <cstring>
#include <cmath>
#include <iomanip>
#include <algorithm>
#include <cstdio>
#include <stack>
#include <queue>
using namespace std;
using ll = long long;
#define up(h,n) for(int i=h;i<=n;i++)
#define down(h,n) for(int i=h;i>=n;i--)
#define wh(x) while(x--)
#define node struct node
#define ios ios::sync_with_stdio(false)
constexpr int N = 305;
constexpr int mod = 1e9 + 7;
typedef int SElemType;
string a;
string b;
void dfs(string s, string k) {
if (s.size() < 1) return;
int t = k.find(s[0]);
dfs(s.substr(1, t), k.substr(0, t));//左子树
dfs(s.substr(t + 1, s.size() - t - 1), k.substr(t + 1, s.size() - t - 1));//右子树
cout << s[0];
}
int main()
{
cin >> a;// 中序
cin >> b;// 前序
dfs(b, a);
return 0;
}
题目链接:淘汰赛
题解:这道题虽然在二叉树里面,但是我没用二叉树去做,循环前后两两相比存大的,然后继续循环总数除以2,直到剩余两个在判断那个小就是亚军输出即可
AC代码:
#include <iostream>
#include <cstring>
#include <cmath>
#include <iomanip>
#include <algorithm>
#include <cstdio>
#include <stack>
#include <queue>
using namespace std;
using ll = long long;
using ull = unsigned long long;
#define up(i, h, n) for (ll i = h; i <= n; i++)
#define down(i, h, n) for(ll i = h; i >= n; i--)
#define wh(x) while(x--)
#define node struct node
#define it ::iterator
#define Ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
constexpr int N = 305;
constexpr int mod = 1e9 + 7;
int n;
node{
int x;
int y;
}a[288];
int main() {
Ios;
cin >> n;
up(i, 1, pow(2, n)) {
a[i].x = i; //编号
cin >> a[i].y; // 能力值
}
int s =1,m=pow(2,n);
while (m > 2) {
s = 1;
for (int i = 1; i+1<= m;i+=2) {
if (a[i].y > a[i + 1].y) a[s++] = a[i]; //记获胜的国家
else a[s++] = a[i + 1];
}
m /= 2; // 国家数量每比一次一半
}
if (a[1].y > a[2].y) cout << a[2].x;
else cout << a[1].x;
return 0;
}