Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function GetHeight(node: PNode): Integer;
- var
- leftHeight, rightHeight: Integer;
- begin
- if node = nil then
- Result := 0
- else
- begin
- leftHeight := GetHeight(node.Left);
- rightHeight := GetHeight(node.Right);
- Result := Max(leftHeight, rightHeight) + 1;
- end;
- end;
- function IsBalanced(node: PNode): Boolean;
- var
- leftHeight, rightHeight: Integer;
- begin
- if node = nil then
- Result := True
- else
- begin
- leftHeight := GetHeight(node.Left);
- rightHeight := GetHeight(node.Right);
- if Abs(leftHeight - rightHeight) <= 1 then
- Result := IsBalanced(node.Left) and IsBalanced(node.Right)
- else
- Result := False;
- end;
- end;
- procedure AddNode(var root: PNode; value: Integer);
- begin
- if root = nil then
- begin
- New(root);
- root.Data := value;
- root.Left := nil;
- root.Right := nil;
- end
- else if value < root.Data then
- AddNode(root.Left, value)
- else
- AddNode(root.Right, value);
- end;
- procedure DeleteNodesToBalance(root: PNode);
- var
- nodesToDelete: array of Integer;
- procedure Traverse(node: PNode);
- begin
- if node <> nil then
- begin
- if not IsBalanced(node) then
- SetLength(nodesToDelete, Length(nodesToDelete) + 1);
- nodesToDelete[High(nodesToDelete)] := node.Data;
- Traverse(node.Left);
- Traverse(node.Right);
- end;
- end;
- var
- i: Integer;
- begin
- Traverse(root);
- if Length(nodesToDelete) > 0 then
- begin
- WriteLn('Values to delete to balance the tree:');
- for i := 0 to High(nodesToDelete) do
- WriteLn(nodesToDelete[i]);
- end
- else
- WriteLn('The tree is already balanced.');
- end;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement