Advertisement
Guest User

Untitled

a guest
Mar 27th, 2017
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.87 KB | None | 0 0
  1. <?php
  2.  
  3. class NodeOfTree
  4. {
  5.     public $tmp;
  6.     public $left;
  7.     public $right;
  8.     public $depth;
  9.  
  10.     public function __construct($tmp)
  11.     {
  12.         $this->tmp = $tmp;
  13.         $this->left = NULL;
  14.         $this->right = NULL;
  15.         $this->depth = NULL;
  16.     }
  17.  
  18.     public function __toString()
  19.     {
  20.         return "$this->tmp";
  21.     }
  22. }
  23.  
  24. class GenerateBinaryTree
  25. {
  26.     public $root;
  27.  
  28.     public function __construct()
  29.     {
  30.         $this->root = NULL;
  31.     }
  32.  
  33.     public function create($tmp)
  34.     {
  35.         if ($this->root == NULL) {
  36.             $this->root = new NodeOfTree($tmp);
  37.         }
  38.         else
  39.         {
  40.  
  41.             $current = $this->root;
  42.             while (true)
  43.             {
  44.                 if ($tmp < $current->tmp)
  45.                 {
  46.  
  47.                     if ($current->left)
  48.                     {
  49.                         $current = $current->left;
  50.                     }
  51.                     else
  52.                         {
  53.                             $current->left = new NodeOfTree($tmp);
  54.                             break;
  55.                         }
  56.                 } else if ($tmp > $current->tmp)
  57.                 {
  58.                     if ($current->right)
  59.                     {
  60.                         $current = $current->right;
  61.                     }
  62.                     else
  63.                     {
  64.                         $current->right = new NodeOfTree($tmp);
  65.                         break;
  66.                     }
  67.                 }
  68.                 else
  69.                 {
  70.                     break;
  71.                 }
  72.             }
  73.         }
  74.     }
  75. }
  76.  
  77. $arr = [2, 3, 4, 7, 1, 4, 7, 4, 2, 5, 7, 9, 3, 2, 5, 7];
  78.  
  79. $tree = new GenerateBinaryTree();
  80.  
  81. for ($i = 0, $n = count($arr); $i < $n; $i++)
  82. {
  83.     $tree->create($arr[$i]);
  84. }
  85. echo 'Array = [ ' . join(', ',$arr) . ' ];';
  86.  
  87. echo '<pre>';
  88. var_dump($tree);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement