要按从上到下,从左到右的顺序查找叶子节点,可以采用广度优先搜索的办法
#include <iostream> #include <queue> using namespace std; typedef struct{ int loc; int left; int right; }unit; int n; unit* a; int father(int); void printLeaf(int); int main() { cin >> n; getchar(); a = (unit*)malloc(n*sizeof(unit)); for (int i = 0; i < n; i++){ a[i].loc = i; a[i].left = a[i].right = -1; } for (int i = 0; i < n; i++){ char left=getchar(); getchar(); char right = getchar(); getchar(); if (‘0‘ <= left && left <= ‘9‘){ a[i].left = left - ‘0‘; } if (‘0‘ <= right&&right <= ‘9‘){ a[i].right = right - ‘0‘; } } int root = father(0); printLeaf(root); cin >> n; } int father(int son) { for (int i = 0; i < n; i++){ if (son == a[i].left || son == a[i].right){ son = i; i = 0; } } return son; } void printLeaf(int root) { queue<unit> q; queue<int> print; q.push(a[root]); while (q.empty() != true){ if (q.front().left == -1 && q.front().right == -1){ print.push(q.front().loc); q.pop(); continue; } if (q.front().left != -1){ q.push(a[q.front().left]); } if (q.front().right != -1){ q.push(a[q.front().right]); } q.pop(); } while (print.size() >= 2){ cout << print.front() << " "; print.pop(); } cout << print.front(); }
时间: 2024-11-08 19:18:33