欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

判断是否为满二叉树

程序员文章站 2024-03-18 22:12:10
...
public class A {


    class Tree{
        int value;
        Tree left;
        Tree right;

        public Tree(int value) {
            this.value = value;
        }
    }

    //判断是否为满二叉树
    public static boolean isFBT(Tree tree){
        //如果为空,不是满二叉树
        if (null == tree){
            return false;
        }
        boolean isLeaf = false;//是否为叶子节点
        Queue<Tree> queue = new LinkedList<>();
        queue.offer(tree);
        while (!queue.isEmpty()){
            Tree root = queue.poll();
            Tree left = root.left;
            Tree right = root.right;
            //1.右孩子不等于空,左孩子等于空
            //2.当前节点为叶子节点,但是左右节点有不为空的
            if ((null != right && null == left) ||
                    (isLeaf && (null != right || null != left))){
                return false;
            }
            if (null != left){
                queue.offer(left);
            }else if (null != right){
                queue.offer(right);
            }else {
                isLeaf = true;
            }
        }

        return true;
    }
}

 

相关标签: 数据结构与算法