How to determine whether a binary tree is complete?

前端 未结 16 1590
渐次进展
渐次进展 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:57

    You can tell if a given binary tree is a left-complete binary tree - better known as a binary heap by ensuring that every node with a right child also has a left child. See below

    bool IsLeftComplete(tree)
    {
    
      if (!tree.Right.IsEmpty && tree.Left.IsEmpty)
        //tree has a right child but no left child, therefore is not a heap
        return false;    
    
      if (tree.Right.IsEmpty && tree.Left.IsEmpty)  
        //no sub-trees, thus is leaf node. All leaves are complete
        return true;
    
      //this level is left complete, check levels below
      return IsLeftComplete(tree.Left) && IsLeftComplete(tree.Right);
    }
    

提交回复
热议问题