【PAT甲级】1099. Build A Binary Search Tree (30)

题目:https://www.patest.cn/contests/pat-a-practise/1099

时隔太久,对二叉树都没有什么印象了……尝试从头分析:
1.首先可以观察发现,如果对输入的数据进行从小到大的排序,那么得到的就是整棵树的中序遍历。
2.在输入中我们知道了每个编号的节点的位置和左右儿子信息。与1结合起来,就得到了整棵树。
3.既然已经知道了整棵树的形状和数值,直接层序遍历就好了。
前面还是挺顺利的!卡在了层序遍历上,上网搜了别人的才知道可以用queue来做。翻笔记的时候看到了之前上数据结构的时候手写的一份非常复杂的代码,觉得现在潜意识里还是有些进步的……

#include<iostream>
#include<stdio.h>
#include<queue>
using namespace std;

struct node {
  int value;
  int left;
  int right;
};

int index = 0;
node trees[100];
int temp, N;
int num[100];

void inorder(int root) {
  if (trees[root].left != -1) {
    inorder(trees[root].left);
  }
  trees[root].value = num[index++];
  if(trees[root].right != -1)
  inorder(trees[root].right);
}

void levelorder(int root) {
  bool isFirst = true;
  queue<node> queues;
  queues.push(trees[root]);
  while (!queues.empty()) {
    node temp = queues.front();
    if (isFirst) {
      cout << temp.value;
      isFirst = !isFirst;
    }
    else {
      cout << " " << temp.value;
    }
    if (temp.left != -1) {
      queues.push(trees[temp.left]);
    }
    if (temp.right != -1) {
      queues.push(trees[temp.right]);
    }
    queues.pop();
  }
  cout << endl;
}

int main() {
  cin >> N;
  for (int i = 0;i < N;i++) {
    cin >> trees[i].left;
    cin >> trees[i].right;
  }
  for(int i = 0;i < N;i++) {
    cin >> num[i];
  }
  //全部数字排序
  for (int i = 0;i < N - 1;i++) {
    for (int j = 0;j < N - 1;j++) {
      if (num[j] > num[j + 1]) {
        temp = num[j + 1];
        num[j + 1] = num[j];
        num[j] = temp;
      }
    }
  }
  inorder(0);
  levelorder(0);
  return 0;
}

猜你喜欢

转载自blog.csdn.net/dango_miracle/article/details/79575813