PAT A1110 Complete Binary Tree (25分)

1. 题目

判断是否完全二叉树

2. 代码

  • 因为index可能有两位数,不能使用char c,应该使用string或者char c[3]。建议使用string比较方便。但是不管哪种都要吸收换行符。
  • 根据是否有父节点判断是否是根结点,这点很常用

1. 使用层序遍历

#include <iostream>
#include <string>
#include <queue>
using namespace std;
const int maxn = 30;
struct node {
  int lchild, rchild;
} Node[maxn];
int N;

bool have_father[maxn] = {false};

int cnt = 1, last = -1;

void layerOrder(int root) {   //完全二叉树左孩子结点 2*i
  queue<int> q;
  q.push(root);
  last = root;
  while (!q.empty()) {
    int front = q.front();
    q.pop();
    if (Node[front].lchild != -1) {
      cnt++;
      last = Node[front].lchild;
      q.push(Node[front].lchild);
    } else break;
    if (Node[front].rchild != -1) {
      cnt++;
      last = Node[front].rchild;
      q.push(Node[front].rchild);
    } else break;
  }
  if (cnt == N) printf("YES %d\n", last);
  else printf("NO %d\n", root);
}

int main() {
  cin >> N;
  for (int i = 0; i < N; ++i) {   //编号从0开始
    cin.ignore();
    string str1, str2;
    cin >> str1 >> str2;
    if (str1 != "-") {    //如果有左孩子
      Node[i].lchild = stoi(str1);
      have_father[stoi(str1)] = true;
    } else {
      Node[i].lchild = -1;
    }

    if (str2 != "-") {    //如果有右孩子
      Node[i].rchild = stoi(str2);
      have_father[stoi(str2)] = true;
    } else {
      Node[i].rchild = -1;
    }

  }
  int root=-1;
  for (int i = 0; i < N; ++i) {   //没有父结点的就是根结点
    if (!have_father[i]) {
      root = i;
      break;
    }
  }
  layerOrder(root);
  return 0;
}

2. 使用DFS

  • 这里搬运了柳神代码
#include <iostream>
#include <string>
using namespace std;
struct node {
  int lchild, rchild;
} Node[1010];

int maxn = -1, ans;

void DFS(int root, int index) {
  if (index > maxn) {
    maxn = index;
    ans = root;
  }
  if (Node[root].lchild != -1) DFS(Node[root].lchild, index * 2);
  if (Node[root].rchild != -1) DFS(Node[root].rchild, index * 2 + 1);
}

int main() {
  int n, root = 0;
  bool have_child[1010] = {false};
  scanf("%d", &n);

  for (int i = 0; i < n; i++) {
    string lchild, rchild;
    cin >> lchild >> rchild;
    if (lchild == "-") Node[i].lchild = -1;
    else {
      Node[i].lchild = stoi(lchild);
      have_child[stoi(lchild)] = true;
    }
    if (rchild == "-") Node[i].rchild = -1;
    else {
      Node[i].rchild = stoi(rchild);
      have_child[stoi(rchild)] = true;
    }
  }

  while (have_child[root]) root++;
  DFS(root, 1);
  if (maxn == n) printf("YES %d", ans);
  else printf("NO %d", root);
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值