第二十八题:如何判断一棵树是一颗全完二叉树?(Java)

题目要求:

如标题:

 分析:

对于二叉树中的任意一个节点,层序遍历二叉树①:如果只有右孩子,没有左孩子,那么该树一定不是完全二叉树;②:第一次发现一个节点有如果左没右,或者左右都没有,那么其后的每一个节点都必须是叶子节点,否则一定不是一颗完全二叉树;

package com.isea.brush.tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 判断一棵树是否是一颗完全二叉树
 */
public class IsCBT {
    private static class Node {
        private Integer data;
        private Node left;
        private Node right;

        public Node(int data) {
            this.data = data;
        }
    }

    public static boolean isCBT(Node head) {
        if (head == null) {
            return true;
        }
        Queue queue = new LinkedList();
        boolean leaf = false;
        Node left = null;
        Node right = null;
        queue.offer(head);
        while (!queue.isEmpty()) {
            head = queue.poll();
            left = head.left;
            right = head.right;
            if ((leaf && (left != null || right != null)) || (left == null && right != null)) {
                return false;
            }
            if (left != null){
                queue.offer(left);
            }
            if (right != null){
                queue.offer(right);
            }
            if (left == null || right == null){
                leaf = true;
            }
        }
        return true;
    }
    public static void main(String[] args) {
        Node head = new Node(4);
        head.left = new Node(2);
        head.right = new Node(6);
        head.left.left = new Node(1);
//        head.left.right = new Node(3);
        head.right.left = new Node(5);

        System.out.println(isCBT(head));  // true
    }
}

 

你可能感兴趣的:(二叉树,算法)