1110 Complete Binary Tree (25分)Java实现

完全二叉树,即从左往右,从上往下排列。
采用深度优先搜索,如果存在以下几种情况则判定不是完全二叉树。
第一步需要判断根结点,定义一个数组a[i],如果他不是别人的子结点就是根结点,即读取输入后其数组值还没变化。

  1. 左子树为空,右子树不为空
  2. 出现第一个左右子树均为空的值后,后续出现左子树或者右子树不为空的结点
    数据结构采用结点数组,flag表示判断结果,first表示第一次出现左右子树均为空的结点
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class P1110 {
    static boolean flag=true;

    static Scanner sc=new Scanner(System.in);
    static int n=sc.nextInt();
    static Node[] nodes=new Node[n];
    public static void main(String[] args) {

        int[] a=new int[n];
        for (int i = 0; i <a.length; i++) {
            a[i]=-1;
        }
        for (int i = 0; i <n ; i++) {
            String s1=sc.next();
            nodes[i]=new Node(-1,-1);
            if(!s1.equals("-")){
                int t=Integer.parseInt(s1);
                a[t]=i;
                nodes[i].left=t;
            }
            String s2=sc.next();
            if(!s2.equals("-")){
                int t=Integer.parseInt(s2);
                a[t]=i;
                nodes[i].right=t;
            }
        }
        int p=0;
        while(a[p]!=-1){
           p++;
        }
        int last=bfs(p,n);
        if(flag){
            System.out.print("YES"+" "+last);
        }else {
            System.out.print("NO"+" "+p);
        }

    }
    public static int bfs(int start,int n){
        Queue<Integer> list=new LinkedList<>();
        list.add(start);
        int last = -1;
        int r;
        boolean first=false;
        while (!list.isEmpty()){
            r=list.remove();
            last=r;
            if(nodes[r].left==-1&&nodes[r].right!=-1){
                flag=false;
                break;
            }
            if(nodes[r].right==-1&&nodes[r].left==-1){
                first=true;
            }
            if(first&&(nodes[r].right!=-1||nodes[r].left!=-1)){
                flag=false;
                break;
            }
            if(nodes[r].left!=-1){
                list.add(nodes[r].left);
            }
            if(nodes[r].right!=-1){
                list.add(nodes[r].right);
            }
        }
        return last;
    }
    public static class Node{
        public int left;
        public int right;

        public Node(int left, int right) {
            this.left = left;
            this.right = right;
        }
    }
}

测试结果

posted @ 2020-10-23 15:56  吾乃七也  阅读(44)  评论(0)    收藏  举报