Skip to content

Commit a723b0d

Browse files
committed
Commit IsCompleteTree() test predicate
1 parent efd3ef1 commit a723b0d

File tree

1 file changed

+43
-1
lines changed

1 file changed

+43
-1
lines changed

binarytree.go

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -403,7 +403,7 @@ func (n *Node[T]) IsDegenerateTree() bool {
403403
// is such a tree, for which the height of the left and right
404404
// sub-trees of each node differ by no more than 1.
405405
func (n *Node[T]) IsBalancedTree() bool {
406-
if n.Left == nil && n.Right == nil {
406+
if n.IsLeafNode() {
407407
return true
408408
}
409409

@@ -443,6 +443,48 @@ func (n *Node[T]) IsBalancedTree() bool {
443443
return true
444444
}
445445

446+
// IsCompleteTree returns true, if the tree is complete. A complete
447+
// binary tree is a binary tree in which every level, except possibly
448+
// the last, is completely filled, and all nodes in the last level are
449+
// as far left as possible.
450+
func (n *Node[T]) IsCompleteTree() bool {
451+
if n.IsLeafNode() {
452+
return true
453+
}
454+
455+
nonFullNodeSeen := false
456+
queue := deque.New[*Node[T]]()
457+
queue.PushBack(n)
458+
459+
for !queue.IsEmpty() {
460+
node, err := queue.PopFront()
461+
if err != nil {
462+
panic(err)
463+
464+
}
465+
466+
if node.Left != nil {
467+
if nonFullNodeSeen {
468+
return false
469+
}
470+
queue.PushBack(node.Left)
471+
}
472+
473+
if !node.IsFullNode() {
474+
nonFullNodeSeen = true
475+
}
476+
477+
if node.Right != nil {
478+
if nonFullNodeSeen {
479+
return false
480+
}
481+
queue.PushBack(node.Right)
482+
}
483+
}
484+
485+
return true
486+
}
487+
446488
// AddAttribute associates an attribute with the node, which will be
447489
// used when generating the Dot representation of the tree.
448490
func (n *Node[T]) AddAttribute(name, value string) {

0 commit comments

Comments
 (0)