github.com/benz9527/toy-box/algo@v0.0.0-20240221120937-66c0c6bd5abd/tree/complete_binary_tree.go (about)

     1  package tree
     2  
     3  func CountNumNodes(n *Node) int {
     4  	if n == nil {
     5  		return 0
     6  	}
     7  
     8  	return 1 + CountNumNodes(n.Left) + CountNumNodes(n.Right)
     9  }
    10  
    11  func IsCompleteBinaryTree(n *Node, idx int, num int) bool {
    12  	if n == nil {
    13  		return true
    14  	}
    15  
    16  	if idx >= num {
    17  		return false
    18  	}
    19  
    20  	return IsCompleteBinaryTree(n.Left, 2*idx+1, num) &&
    21  		IsCompleteBinaryTree(n.Right, 2*idx+2, num)
    22  }