958. Check Completeness of a Binary Tree

958. Check Completeness of a Binary Tree

//https://leetcode.com/problems/check-completeness-of-a-binary-tree/description/

class TreeNode(var `val`: Int) {
    var left: TreeNode? = null
    var right: TreeNode? = null
}

class Solution {
    fun isCompleteTree(root: TreeNode?): Boolean {
        if (root == null) {
            return false
        }
        val linkedList = LinkedList<TreeNode>()
        linkedList.add(root)
        while (linkedList.peek()!=null) {
            //if popped node is not null, then add its left and right child, no matter if they are null or not
            val cur = linkedList.poll()
            linkedList.offer(cur.left)
            linkedList.offer(cur.right)
        }
        //get right node first
        while (linkedList.isNotEmpty() && linkedList.peek()==null){
            linkedList.poll()
        }
        return linkedList.isEmpty()
    }
}
原文地址:https://www.cnblogs.com/johnnyzhao/p/11429381.html