網易筆試題判斷二叉樹是否爲遞增二叉樹

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;

public class TreeExercise {
    static class Tree{
        int data;
        int left;
        int right;
    }
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N =Integer.parseInt(br.readLine());
        for(int i=0;i<N;i++){
            int n = Integer.parseInt(br.readLine());
            //int[] num = new int[n];
            Tree[] num = new Tree[n];
            for(int j=0;j<n;j++){

                String[] nu = br.readLine().split(" ");
                num[j] = new Tree();
                num[j].data=Integer.parseInt(nu[0]);
                num[j].left=Integer.parseInt(nu[1]);
                num[j].right=Integer.parseInt(nu[2]);
            }
            int root = getRoot(num,n);
            Boolean rr = isDuo(num,root);
            if(rr){
                System.out.println("YES");
            }else{
                System.out.println("NO");
            }
        }
    }

    public static int getRoot(Tree num[],int n){
        int[] check = new int[n];
        int c = 0;
        for(int m=0;m<n;m++){
            check[m]=0;
        }
        for(int a = 0;a<n;a++){
            if(num[a].left!=-1){
                check[num[a].left]+=1;
            }
            if(num[a].right!=-1){
                check[num[a].right]+=1;
            }
        }
        for(int b =0;b<n;b++){
            if (check[b]==0){
                c = b;
                break;
            }

        }
        return c;
    }
    public static boolean isDuo(Tree num[],int root){
        if (num.length==1) return true;
        Queue<Tree> que = new LinkedList();
        que.add(num[root]);
        int a = 0;

        while (!que.isEmpty()){
            int b = 0;
            int siz = que.size();
            for (int i=0;i<siz;i++){
                Tree node = que.remove();
                b+=node.data;
                if(node.left!=-1) que.add(num[node.left]);
                if(node.right!=-1) que.add(num[node.right]);
            }
            if(a>=b){
                return false;
            }else{
                a=b;
            }
        }
        return true;
    }

}

主要用到了數組建樹,隊列對樹層次遍歷知識點。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章