List Leaves
题目大意:给定一棵二叉树,输出所有叶节点的序号。
解题思路:层次遍历二叉树,输出所有叶节点的序号。
//结点类
class Node0{
int data;
int leftSon;
int rightSon;
}
//队列类
class Queue_Tree{
private int maxSize;
private int[] queArray;
private int front;
private int rear;
private int num;
//构造函数,初始化队列
public Queue_Tree(int s){
maxSize = s;
queArray = new int[maxSize];
front = 0;
rear = -1;
num = 0;
}
//队列尾部插入元素
public void insert(int value){
if(rear == maxSize - 1){
rear = -1;
}else{
queArray[++rear] = value;
num++;
}
}
//队列头部取出元素
public int remove(){
int temp = queArray[front];
int a = -1;
queArray[front] = 0;
front++;
if(front == maxSize){
front = 0;
}
num--;
a = temp;
return a;
}
//打印队列中的元素
public void display(){
int temp = num;
while( !isEmpty()){
System.out.println(remove()+" ");
}
System.out.println();
num = temp;
}
//判断队列是否为空
public boolean isEmpty(){
return (num == 0);
}
//判断队列是否已满
public boolean isFull(){
return (num == maxSize);
}
//返回队列的元素个数
public int size(){
return num;
}
}
//主类
class Main{
public static Node0[] tree = new Node0[10];
//建一棵二叉树,找到根节点
public static int CreateTree(Scanner sc, int n){
int root = 0;
int []check = new int[n]; //数组初始化就都为0
for (int i = 0; i < n; i++) {
Node0 node = new Node0();
//判断输入的左儿子
char ch = sc.next().charAt(0);
if(ch == '-'){
node.leftSon = -1;
}else{
node.leftSon = ch - 48;//char类型减去48就是它对应的int的值
check[node.leftSon] = 1;
}
//判断输入的右儿子
ch = sc.next().charAt(0);
if(ch == '-'){
node.rightSon = -1;
}else{
node.rightSon = ch - 48;
check[node.rightSon] = 1;
}
node.data = i;
tree[i] = node;
}
//找到根节点,
for (int k = 0; k < check.length; k++) {
if(check[k] == 0){
root = k;
}
}
return root;
}
//层次遍历二叉树
public static void find(int head, int num){
if( num == 0){
return;
}
int a = 0;
//新建一个队列
Queue_Tree queue = new Queue_Tree(num);
queue.insert(head);
while( !queue.isEmpty()){
head = queue.remove();
//判断是否是叶节点
if(tree[head].leftSon==-1 && tree[head].rightSon == -1){
if(a++ == 0){
System.out.print(head);
}
else{
System.out.print(" "+head);
}
}
//如果左右孩子不为空,则左右孩子入队
if(tree[head].leftSon != -1){
queue.insert(tree[head].leftSon);
}
if(tree[head].rightSon != -1){
queue.insert(tree[head].rightSon);
}
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int head = CreateTree(in, num);
find(head, num);
}
}
这道题,主要还是建一棵二叉树,找到根节点,然后利用队列先进先出的原理,如果进入队列的那一个节点没有左右儿子节点,则输出该节点的序号,用递归。