gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
Реши задачу на Delphi: Для заданного двоичного дерева подсчитать длину его внутреннего…
- User
Реши задачу на Delphi: Для заданного двоичного дерева подсчитать длину его внутреннего пути (сумма длин для всех его вершин)
- Assistant
Вот решение на Delphi:
program BinaryTree; type PNode = ^TNode; TNode = record data: Integer; left: PNode; right: PNode; end; function NewNode(data: Integer): PNode; begin New(Result); Result^.data := data; Result^.left := nil; Result^.right := nil; end; function Insert(root: PNode; data: Integer): PNode; begin if root = nil then Result := NewNode(data) else if data < root^.data then root^.left := Insert(root^.left, data) else root^.right := Insert(root^.right, data); end; function CalcInternalPath(node: PNode; depth: Integer): Integer; begin if node = nil then Result := 0 else begin Result := depth + CalcInternalPath(node^.left, depth + 1) + CalcInternalPath(node^.right, depth + 1); end; end; var root: PNode; internalPath: Integer; begin root := nil; // Вставка элементов в дерево root := Insert(root, 5); root := Insert(root, 3); root := Insert(root, 2); root := Insert(root, 4); root := Insert(root, 7); root := Insert(root, 6); root := Insert(root, 8); // Вычисление длины внутреннего пути internalPath := CalcInternalPath(root, 0); WriteLn('Длина внутреннего пути: ', internalPath); end.