CodeKnight & ForgeBlink
Hey ForgeBlink, just finished a new algorithm that builds a perfectly balanced binary tree with a symmetrical output. Want to compare notes?
Nice work. Share the code and the symmetry metrics so I can check the balance against my own calculations.
class BalancedTree:
def __init__(self, values):
self.values = sorted(values)
self.root = self.build(0, len(self.values) - 1)
def build(self, left, right):
if left > right:
return None
mid = (left + right) // 2
node = Node(self.values[mid])
node.left = self.build(left, mid - 1)
node.right = self.build(mid + 1, right)
return node
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def symmetry_metric(root):
if not root:
return 1.0
left_depth = max_depth(root.left)
right_depth = max_depth(root.right)
return 1.0 - abs(left_depth - right_depth) / max(left_depth, right_depth)
def max_depth(node):
if not node:
return 0
return 1 + max(max_depth(node.left), max_depth(node.right))
# Example usage
values = [1, 2, 3, 4, 5, 6, 7]
tree = BalancedTree(values)
print("Symmetry metric:", symmetry_metric(tree.root))