用Delphi写一个森林转树
时间: 2023-12-08 10:05:20 浏览: 38
森林转树是指将多棵树合并成一棵树。下面是用 Delphi 实现森林转树的示例代码:
```delphi
program ForestToTree;
uses
SysUtils;
type
PNode = ^TNode;
TNode = record
Value: Integer;
Parent: PNode;
Child: PNode;
Sibling: PNode;
end;
var
Root: PNode;
procedure InsertNode(Parent, Child: PNode);
begin
Child^.Parent := Parent;
Child^.Sibling := Parent^.Child;
Parent^.Child := Child;
end;
procedure AddTree(Root: PNode);
var
Node: PNode;
begin
Node := Root;
while Assigned(Node) do
begin
if Assigned(Node^.Child) then
begin
AddTree(Node^.Child);
Node^.Child := nil;
end;
if Assigned(Node^.Sibling) then
begin
InsertNode(Root, Node^.Sibling);
Node^.Sibling := nil;
end;
Node := Node^.Sibling;
end;
end;
procedure ForestToTree(Root: PNode);
begin
if not Assigned(Root) then Exit;
AddTree(Root);
ForestToTree(Root^.Sibling);
ForestToTree(Root^.Child);
end;
procedure PrintTree(Root: PNode; Indent: Integer);
var
I: Integer;
begin
for I := 1 to Indent do Write(' ');
WriteLn(Root^.Value);
if Assigned(Root^.Child) then
PrintTree(Root^.Child, Indent + 2);
if Assigned(Root^.Sibling) then
PrintTree(Root^.Sibling, Indent);
end;
procedure BuildForest;
var
Node1, Node2, Node3, Node4, Node5, Node6: PNode;
begin
New(Node1);
New(Node2);
New(Node3);
New(Node4);
New(Node5);
New(Node6);
Node1^.Value := 1;
Node2^.Value := 2;
Node3^.Value := 3;
Node4^.Value := 4;
Node5^.Value := 5;
Node6^.Value := 6;
InsertNode(Node1, Node2);
InsertNode(Node1, Node3);
InsertNode(Node2, Node4);
InsertNode(Node2, Node5);
InsertNode(Node3, Node6);
Root := Node1;
end;
begin
BuildForest;
ForestToTree(Root);
PrintTree(Root, 0);
end.
```
这个程序中,我们定义了一个节点类型 `TNode`,包含一个整数值 `Value`,一个父节点指针 `Parent`,一个子节点指针 `Child` 和一个兄弟节点指针 `Sibling`。然后我们定义了一个 `InsertNode` 函数,用于将一个节点插入到一个节点的子节点列表中。接着是 `AddTree` 函数,用于将一个子树添加到根节点的子节点列表中。最后是 `ForestToTree` 函数,用于将整个森林转换为一棵树,并输出树的结构。在主程序中,我们构建了一个简单的森林,然后调用 `ForestToTree` 函数,将其转换为一棵树,并输出树的结构。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)