Java judges whether a tree is a complete binary tree

Determine whether a tree is a complete binary tree

2023 01 10 107 00 46 07
I won’t talk about the definition of a complete binary tree, so how do we judge whether a tree is an ordinary tree or a complete binary tree?

Title description :
Given the head node TreeNode root of a binary tree, it is required to return true or false.

insert image description here

Code :
In fact, it is the idea of ​​​​using layer order traversal

 boolean isCompleteTree(TreeNode root){
    
    
        if(root == null){
    
    
            return true;
        }
        Deque<TreeNode> deque = new LinkedList<>();
        deque.offer(root);
        while(!deque.isEmpty()){
    
    
            TreeNode cur = deque.poll();
            if(cur != null){
    
    
                deque.offer(cur.left);
                deque.offer(cur.right);
            }
            else{
    
    
                break;
            }
        }
        while(!deque.isEmpty()){
    
    
            TreeNode cur = deque.poll();
            if(cur != null){
    
    
                return false;
            }
        }return true;
    }


Definition of the test tree

ublic class MyBinaryTree {
    
    

    class TreeNode {
    
    
        char val;
        TreeNode left;
        TreeNode right;

        public TreeNode(char val) {
    
    
            this.val = val;
            this.left = null;
            this.right = null;
        }
    }

    public TreeNode root;//根节点
}

Test class

public class Test {
    
    
    public static void main(String[] args) {
    
    
        MyBinaryTree myBinaryTree1 = new MyBinaryTree();
        MyBinaryTree.TreeNode root = myBinaryTree1.root;
        MyBinaryTree.TreeNode A = new MyBinaryTree().new TreeNode('A');
        MyBinaryTree.TreeNode B = new MyBinaryTree().new TreeNode('B');
        MyBinaryTree.TreeNode C = new MyBinaryTree().new TreeNode('C');
        MyBinaryTree.TreeNode D = new MyBinaryTree().new TreeNode('D');
        MyBinaryTree.TreeNode E = new MyBinaryTree().new TreeNode('E');
        MyBinaryTree.TreeNode F = new MyBinaryTree().new TreeNode('F');
        MyBinaryTree.TreeNode G = new MyBinaryTree().new TreeNode('G');
        MyBinaryTree.TreeNode H = new MyBinaryTree().new TreeNode('H');
        A.left = B;A.right = C;B.left = D;B.right = E;E.right = H;C.left = F;C.right = G;
        root = A;
        //判断是不是完全二叉树
        System.out.println("判断是不是完全二叉树");
        System.out.println(myBinaryTree1.isCompleteTree(root));
        }
 }

result
insert image description here

Guess you like

Origin blog.csdn.net/baixian110/article/details/131014164