判断完全二叉树

1.任一节点,有右孩子无左孩子直接返回false
2.在不违规1的条件下,如果遇到了第一个左右子不全,后续都是叶子节点
(如果遇到了第一个左右不全,后续有一个不是叶子节点那么返回false)

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Stack;

public class testCBT{
    public static class Node{
        public int value;
        public Node left;
        public Node right;

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

    public static boolean checkCBT(Node head){
       if(head == null){
           return true;
       }
       LinkedList<Node> queue = new LinkedList<>();
       boolean leaf = false;
       Node l = null;
       Node r = null;
       queue.add(head);
       while(!queue.isEmpty()){
            head = queue.poll();
            l = head.left;
            r = head.right;

            if(
                (l == null && r != null)
                    ||
                (leaf && !(l == null && r == null))//如果遇到第一个左右子不全,而且不是叶子节点则不是CBT
            ){
                return false;
            }     
            
            if(l == null || r == null){
                leaf = true;//相当于一个开关,遇到第一个左右子不全的
            }

           if(l != null){
               queue.add(l);
           }
           if(r != null){
               queue.add(r);
           }
       }
       return true;

    }

    
 
}

你可能感兴趣的:(数据结构)