Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class NodeOfTree
- {
- public $tmp;
- public $left;
- public $right;
- public $depth;
- public function __construct($tmp)
- {
- $this->tmp = $tmp;
- $this->left = NULL;
- $this->right = NULL;
- $this->depth = NULL;
- }
- public function __toString()
- {
- return "$this->tmp";
- }
- }
- class GenerateBinaryTree
- {
- public $root;
- public function __construct()
- {
- $this->root = NULL;
- }
- public function create($tmp)
- {
- if ($this->root == NULL) {
- $this->root = new NodeOfTree($tmp);
- }
- else
- {
- $current = $this->root;
- while (true)
- {
- if ($tmp < $current->tmp)
- {
- if ($current->left)
- {
- $current = $current->left;
- }
- else
- {
- $current->left = new NodeOfTree($tmp);
- break;
- }
- } else if ($tmp > $current->tmp)
- {
- if ($current->right)
- {
- $current = $current->right;
- }
- else
- {
- $current->right = new NodeOfTree($tmp);
- break;
- }
- }
- else
- {
- break;
- }
- }
- }
- }
- }
- $arr = [2, 3, 4, 7, 1, 4, 7, 4, 2, 5, 7, 9, 3, 2, 5, 7];
- $tree = new GenerateBinaryTree();
- for ($i = 0, $n = count($arr); $i < $n; $i++)
- {
- $tree->create($arr[$i]);
- }
- echo 'Array = [ ' . join(', ',$arr) . ' ];';
- echo '<pre>';
- var_dump($tree);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement