Advertisement
dxvmxnd

Untitled

Mar 17th, 2024
20
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. function GetHeight(node: PNode): Integer;
  2. var
  3. leftHeight, rightHeight: Integer;
  4. begin
  5. if node = nil then
  6. Result := 0
  7. else
  8. begin
  9. leftHeight := GetHeight(node.Left);
  10. rightHeight := GetHeight(node.Right);
  11. Result := Max(leftHeight, rightHeight) + 1;
  12. end;
  13. end;
  14.  
  15. function IsBalanced(node: PNode): Boolean;
  16. var
  17. leftHeight, rightHeight: Integer;
  18. begin
  19. if node = nil then
  20. Result := True
  21. else
  22. begin
  23. leftHeight := GetHeight(node.Left);
  24. rightHeight := GetHeight(node.Right);
  25. if Abs(leftHeight - rightHeight) <= 1 then
  26. Result := IsBalanced(node.Left) and IsBalanced(node.Right)
  27. else
  28. Result := False;
  29. end;
  30. end;
  31.  
  32. procedure AddNode(var root: PNode; value: Integer);
  33. begin
  34. if root = nil then
  35. begin
  36. New(root);
  37. root.Data := value;
  38. root.Left := nil;
  39. root.Right := nil;
  40. end
  41. else if value < root.Data then
  42. AddNode(root.Left, value)
  43. else
  44. AddNode(root.Right, value);
  45. end;
  46.  
  47. procedure DeleteNodesToBalance(root: PNode);
  48. var
  49. nodesToDelete: array of Integer;
  50.  
  51. procedure Traverse(node: PNode);
  52. begin
  53. if node <> nil then
  54. begin
  55. if not IsBalanced(node) then
  56. SetLength(nodesToDelete, Length(nodesToDelete) + 1);
  57. nodesToDelete[High(nodesToDelete)] := node.Data;
  58.  
  59. Traverse(node.Left);
  60. Traverse(node.Right);
  61. end;
  62. end;
  63.  
  64. var
  65. i: Integer;
  66. begin
  67. Traverse(root);
  68.  
  69. if Length(nodesToDelete) > 0 then
  70. begin
  71. WriteLn('Values to delete to balance the tree:');
  72. for i := 0 to High(nodesToDelete) do
  73. WriteLn(nodesToDelete[i]);
  74. end
  75. else
  76. WriteLn('The tree is already balanced.');
  77. end;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement