github.com/benz9527/toy-box/algo@v0.0.0-20240221120937-66c0c6bd5abd/tree/perfect_binary_tree.go (about) 1 package tree 2 3 func Depth(n *Node) int { 4 d := 0 5 for n != nil { 6 d++ 7 n = n.Left 8 } 9 return d 10 } 11 12 func isPerfectBinaryTree(n *Node, depth int, level int) bool { 13 if n == nil { 14 return true 15 } 16 17 if n.Left == nil && n.Right == nil { 18 return depth == (level + 1) 19 } 20 21 if n.Left == nil || n.Right == nil { 22 return false 23 } 24 25 // Not a tail recursion. 26 return isPerfectBinaryTree(n.Left, depth, level+1) && 27 isPerfectBinaryTree(n.Right, depth, level+1) 28 } 29 30 func IsPerfectBinaryTree(n *Node) bool { 31 depth := Depth(n) 32 return isPerfectBinaryTree(n, depth, 0) 33 }