是否爲完全二叉樹

7-13 是否完全二叉搜索樹(30 分)
將一系列給定數字順序插入一個初始爲空的二叉搜索樹(定義爲左子樹鍵值大,右子樹鍵值小),你需要判斷最後的樹是否一棵完全二叉樹,並且給出其層序遍歷的結果。


輸入格式:
輸入第一行給出一個不超過20的正整數N;第二行給出N個互不相同的正整數,其間以空格分隔。


輸出格式:
將輸入的N個正整數順序插入一個初始爲空的二叉搜索樹。在第一行中輸出結果樹的層序遍歷結果,數字間以1個空格分隔,行的首尾不得有多餘空格。第二行輸出YES,如果該樹是完全二叉樹;否則輸出NO。


輸入樣例1:
9
38 45 42 24 58 30 67 12 51
輸出樣例1:
38 45 24 58 42 30 12 67 51
YES
輸入樣例2:
8
38 24 12 45 58 67 42 51
輸出樣例2:
38 45 24 58 42 12 67 51

NO

分析:遞歸建立二叉樹,判斷是否爲完全爲二叉樹的方法:建成的二叉樹的節點編號爲1到n的值都是非空的。看代碼:

import java.util.*;
public class Main {
    static Scanner in = new Scanner(System.in);
    static int maxn = 1<<20;
    static int n,a,m;
    static int[] tree = new int[maxn];
    static void create(int x) {//建立二叉樹,遞歸調用
    	if(tree[x] == 0)
    		tree[x] = a;
    	else if(a > tree[x])//大於父節點,左子樹
    		create(x*2);
    	else//小於父節點,右子樹
    		create(x*2+1);
    }
	public static void main(String[] args) {
		Arrays.fill(tree, 0);
		n = in.nextInt();
		for(int i = 0;i < n;i++) {
			a = in.nextInt();
			create(1);
		}
		boolean f = false;
		for(int i = 1,cnt = 1; cnt <= n; ++i){  
	        if(tree[i] == 0)//序號不是一一對應,不是完全二叉樹
	        	f = true;  
	        else{  
	            System.out.print(tree[i]);
	            if(cnt != n)
	            	System.out.print(" ");  
	            cnt++;  //總的節點個數要滿足
	        }  
	    }  
		System.out.println();
		if(f) 		
			System.out.println("No");
		else 
			System.out.println("YES");		
	}
}

發佈了262 篇原創文章 · 獲贊 14 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章