Leetcode - Delete Node in a BST
Leetcode - Construct Binary Tree from Preorder and Inorder Traversal

Leetcode - Check Completeness of a Binary Tree

violet posted @ Apr 21, 2020 07:23:16 AM in 算法 with tags Algorithm Golang tree , 239 阅读

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

Given a binary tree, determine if it is a complete binary tree.

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

 

Example 1:

Input: [1,2,3,4,5,6]
Output: true
Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.

 

Use a queue to add all nodes. If there is a nil node before a non-nil node in the queue, then it is not a completed tree.

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isCompleteTree(root *TreeNode) bool {
    queue := []*TreeNode{root}
    final := false
    for len(queue) != 0 {
        node := queue[0]
        queue = queue[1:]
        if node == nil {
            final = true
        } else {
            if final {
                return false
            }
            queue = append(queue, node.Left)
            queue = append(queue, node.Right)
        }
    }
    return true
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter