How to determine whether a binary tree is complete?

前端 未结 16 1592
渐次进展
渐次进展 2021-01-02 19:15

A complete binary tree is defined as a binary tree in which every level, except possibly the deepest, is completely filled. At deepest level, all nodes must be as far left a

16条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-02 19:46

    There may be one possible algorithm which I feel would solve this problem. Consider the tree:

    Level 0:    a  
    Level 1:  b   c  
    Level 2: d e f g  
    
    • We employ breadth first traversal.

    • For each enqueued element in the queue we have to make three checks in order:

      1. If there is a single child or no child terminate; else, check 2.
      2. If there exist both children set a global flag = true.
        1. Set flags for each node in the queue as true: flag[b] = flag[c] = true.
        2. Check for each entry if they have left n right child n then set the flags or reset them to false.
        3. (Dequeue) if(queue_empty())
          compare all node flags[]... if all true global_flag = true else global_flag = false.
        4. If global_flag = true go for proceed with next level in breadth first traversal else terminate

    Advantage: entire tree may not be traversed
    Overhead: maintaining flag entries

提交回复
热议问题