03-树2. List Leaves (25)

http://www.patest.cn/contests/mooc-ds/03-%E6%A0%912

/* 并查集 和 树的递归遍历找叶子节点 */
#include <cstdio> 
#include <sstream> 
#include <cstring> 
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
#include <sstream>
#include <cmath>
#include <stack>

using namespace std;

#define N 11

int n;

struct mydata{
  int no;
  int left;
  int right;
};

typedef struct node{
  int data;
  struct node* left;
  struct node* right;
  node(int _data){
    data = _data;
    left = NULL;
    right = NULL;
  }
}Bnode;

//int str2int(string s)
//{
// if (s == "-")
// return -1;
// stringstream ss;
// ss << s;
// int tmp;
// ss >> tmp;
// return tmp;
//}


mydata a[N];

int father[N];
int find(int x)
{
  if (x == father[x])
    return x;
  return father[x] = find(father[x]);
}

void merge(int x, int y)
{
  father[find(y)] = find(x);
}

Bnode* root;

Bnode* createtree(Bnode* root ,int rootNum)
{
  if (rootNum == -1)
    return NULL;
  root = new node(rootNum);
  if (a[rootNum].left == -1)
  {
    root->left = NULL;
  }
  else{
    root->left = createtree(root->left, a[rootNum].left);
  }
  if (a[rootNum].right == -1)
  {
    root->right = NULL;
  }
  else{
    root->right = createtree(root->right, a[rootNum].right);
  }
  return root;
}

vector<int> v;

void inorder(Bnode* root)
{
  queue<Bnode*> que;
  que.push(root);
  while (!que.empty())
  {
    Bnode* bt = que.front();
    que.pop();
    if (bt->left == NULL && bt->right == NULL)
      v.push_back(bt->data);
    else {
      if (bt->left != NULL)
      {
        que.push(bt->left);
      }
      if(bt->right != NULL)
      {
        que.push(bt->right);
      }
    }
  }
}

int main()
{
  //freopen("in", "r", stdin);
  scanf("%d\n", &n);
  int i;
  for (i = 0; i < n; i++)
  {
    father[i] = i;
  }
  mydata dt;
  char c1, c2;
  for (i = 0; i < n; i++)
  {
    scanf("%c %c\n", &c1, &c2);
    dt.no = i;
    if (c1 == '-')
    {
      dt.left = -1;
    }
    else{
      dt.left = (int)(c1 - '0');
      if (find(i) != find(dt.left))
      {
        merge(i, dt.left);
      }
    }
    if (c2 == '-')
    {
      dt.right = -1;
    }
    else{
      dt.right = (int)(c2 - '0');
      if (find(i) != find(dt.right))
      {
        merge(i, dt.right);
      }
    }
    a[i] = dt;
  }

  int rootNum = find(0);
  root = NULL;
  root = createtree(root, rootNum);

  inorder(root);
  int len = v.size();
  printf("%d", v[0]);
  for (i = 1; i < len; i++)
  {
    printf(" %d", v[i]);
  }
  printf("\n");
  return 0;
}

你可能感兴趣的:(03-树2. List Leaves (25))