完全二叉树判断(java)

6、完全二叉树

1、定义

  • [1、任意节点有右无左false

  • 在 [1 不违规的条件下,如果遇到第一个左右子都不全—且下一个不为叶节点—返回false

  • 采用宽度优先遍历

  • //判断是否为完全二叉树
        public boolean isCbt(TreeNode treeNode){
            if (treeNode == null){
                return true;
            }
            Queue<TreeNode> queue = new LinkedList<>();
            TreeNode l = null;
            TreeNode r = null;
            boolean flag = false;
            queue.add(treeNode);
            while (!queue.isEmpty()){
                treeNode = queue.poll();
                l = treeNode.left;
                r = treeNode.right;
                if (((flag && (l !=null || r !=null))) 
                    || (l == null && r != null)){
                 //条件1---当遇到左右不全有的节点时,切下一个节点有左或者有右孩子时返回false
                 //条件2---当有右无左直接false
                    return false;
                }
                if (l !=null){
                    queue.add(l);
                }
                if (r != null){
                    queue.add(r);
                }
                if (l == null || r == null){  //遇到左右不全有的节点时开关打开
                    flag = true;
                }
            }
            return true;
        }
    
要创建完全二叉树,可以使用队列来辅助构建。下面是一个示例的Java代码: ```java // 设置TreeNode为内部类:二叉的存储结构 private class TreeNode { private T data; // 数据域 private TreeNode left; // 左孩子指针 private TreeNode right; // 右孩子指针 public TreeNode(T data) { this.data = data; } } /** * 利用队列创建完全二叉树 * @param data 节点数据 */ public void add(T data) { if (this.root == null) { this.root = new TreeNode(data); queue.add(this.root); } else { if (!queue.isEmpty()) { TreeNode node = queue.peek(); if (node.left == null) { node.left = new TreeNode(data); queue.add(node.left); } else { // 左子不为空,直接操作右子 node.right = new TreeNode(data); queue.add(node.right); // 这时左右子都不为空了,当前节点出队 queue.poll(); } } } } ``` 上述代码中,首先定义了一个内部类TreeNode,表示二叉的节点。接着,使用add方法来逐个添加节点,这里使用队列queue来辅助构建完全二叉树。当为空时,直接创建根节点,并将根节点加入队列。否则,从队列中取出第一个节点,并判断其左子是否为空。若为空,创建左子节点,并将其加入队列。若左子不为空,直接操作右子,并将右子节点加入队列。最后,当左右子都不为空时,将当前节点出队。完成所有节点的添加后,即可得到一个完全二叉树。 请注意,这只是一个示例的实现方法,具体的实现可能会根据需求而有所变化。如果有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值