Completed
Push — master ( 7af6a9...1c5b8d )
by Siro Díaz
02:01
created

BinaryTreeAbstract::postorder()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/**
3
 * DataStructures for PHP
4
 *
5
 * @link      https://github.com/SiroDiaz/DataStructures
6
 * @copyright Copyright (c) 2017 Siro Díaz Palazón
7
 * @license   https://github.com/SiroDiaz/DataStructures/blob/master/README.md (MIT License)
8
 */
9
namespace DataStructures\Trees;
10
11
use DataStructures\Trees\Interfaces\TreeInterface;
12
use DataStructures\Trees\Interfaces\BinaryNodeInterface;
13
14
/**
15
 * BinaryTreeAbstract
16
 * 
17
 * BinaryTreeAbstract class is an abstract class that implements
18
 * common binary trees methods.
19
 *
20
 * @author Siro Diaz Palazon <[email protected]>
21
 */
22
abstract class BinaryTreeAbstract implements TreeInterface {
23
    protected $root;
24
    protected $size;
25
26
    /**
27
     * Checks if the tree is empty.
28
     *
29
     * @return boolean true if is empty, else false.
30
     */
31
    public function empty() {
32
        return $this->root === null;
33
    }
34
35
    /**
36
     * Returns the tree size.
37
     *
38
     * @return int the length
39
     */
40
    public function size() {
41
        return $this->size;
42
    }
43
44
    public function put($key, $data) {
45
46
    }
47
48
    public function putOrUpdate($key, $data) {
49
50
    }
51
52
    /**
53
     * Retrieve the data stored in the tree.
54
     *
55
     * @param int|string $key the key to identify the data.
56
     * @return mixed
57
     */
58
    public function get($key){
59
        if($this->root === null) {
60
            return null;
61
        }
62
63
        $node = $this->root;
64
        while($node !== null) {
65
            if($key < $node->key) {
66
                $node = $node->left;
67
            } else if($key > $node->key) {
68
                $node = $node->right;
69
            } else {
70
                return $node->data;
71
            }
72
        }
73
74
        return null;
75
    }
76
77
    /**
78
     * Returns the root node.
79
     *
80
     * @return DataStructures\Trees\Nodes\BSTNode|null the root node.
81
     */
82
    public function getRoot(){
83
        return $this->root;
84
    }
85
86
    /**
87
     * Looks for the node with the given key.
88
     *
89
     * @param int|string $key the key used to look for.
90
     * @return bool true if was found.
91
     */
92
    public function exists($key){
93
        // $this->_exists($this->root, $key); for recursive search
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
94
        if($this->root === null) {
95
            return false;
96
        }
97
98
        if($this->root->key === $key) {
99
            return true;
100
        } else {
101
            $node = $this->root;
102
            while($node !== null) {
103
                if($key < $node->key) {
104
                    $node = $node->left;
105
                } else if($key > $node->key) {
106
                    $node = $node->right;
107
                } else {
108
                    return true;
109
                }
110
            }
111
        }
112
113
        return false;
114
    }
115
116
    /**
117
     * Method that retrieves true if found a node with the specified key.
118
     * It's the recursive version of exists method and it's used internally
119
     * for traverse through a root node.
120
     *
121
     * @param DataStructures\Trees\Nodes\BSTNode|null $node the root node.
122
     * @param int|string $key the key used to look for.
123
     * @return bool true if exists a node with that key.
124
     */
125
    private function _exists($node, $key) : bool {
126
        if($node === null) {
127
            return false;
128
        }
129
130
        if($node->key === $key) {
131
            return true;
132
        } else if($key < $node->key) {
133
            return $this->_exists($node->left, $key);
134
        } else if($key > $node->key) {
135
            return $this->_exists($node->right, $key);
136
        }
137
    }
138
139
    public function floor($key){}
140
    public function ceil($key){}
141
142
    /**
143
     * Gets the node with the minimum key. The most left and more bottom.
144
     * 
145
     * @return DataStructures\Trees\Nodes\BSTNode|null the minum node or
146
     *  null if the tree is empty.
147
     */
148
    public function min() {
149
        if($this->root === null) {
150
            return null;
151
        }
152
153
        if($this->root->left === null) {
154
            return $this->root;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->root; (DataStructures\Trees\Nodes\BSTNode) is incompatible with the return type documented by DataStructures\Trees\BinaryTreeAbstract::min of type DataStructures\Trees\Dat...rees\Nodes\BSTNode|null.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
155
        }
156
157
        $current = $this->root;
158
        while($current->left !== null) {
159
            $current = $current->left;
160
        }
161
162
        return $current;
163
    }
164
165
    /**
166
     * Gets the node with the maximum key. The most right and more bottom.
167
     * 
168
     * @return DataStructures\Trees\Nodes\BSTNode|null the maximum node or
169
     *  null if the tree is empty.
170
     */
171
    public function max() {
172
        if($this->root === null) {
173
            return null;
174
        }
175
176
        if($this->root->right === null) {
177
            return $this->root;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->root; (DataStructures\Trees\Nodes\BSTNode) is incompatible with the return type documented by DataStructures\Trees\BinaryTreeAbstract::max of type DataStructures\Trees\Dat...rees\Nodes\BSTNode|null.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
178
        }
179
180
        $node = $this->root;
181
        while($node->right !== null) {
182
            $node = $node->right;
183
        }
184
185
        return $node;
186
    }
187
188
    /**
189
     * Returns the minimum node from a given node in position X.
190
     *
191
     * @param DataStructures\Trees\Nodes\BSTNode $node the start point.
192
     * @return DataStructures\Trees\Nodes\BSTNode|null the minimum node.
193
     */
194 View Code Duplication
    private function getMinNode(BinaryNodeInterface $node = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
195
        if($node === null) {
196
            return null;
197
        }
198
199
        while($node->left !== null) {
200
            $node = $node->left;
201
        }
202
203
        return $node;
204
    }
205
206
    /**
207
     * Returns the maximum node from a given node in position X.
208
     *
209
     * @param DataStructures\Trees\Nodes\BSTNode $node the start point.
210
     * @return DataStructures\Trees\Nodes\BSTNode|null the maximum node.
211
     */
212 View Code Duplication
    private function getMaxNode(BinaryNodeInterface $node = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
213
        if($node === null) {
214
            return null;
215
        }
216
        
217
        while($node->right !== null) {
218
            $node = $node->right;
219
        }
220
221
        return $node;
222
    }
223
    
224
    /**
225
     * Deletes the node with the minimum key and returns it. The most left and more bottom.
226
     * 
227
     * @param DataStructures\Trees\Nodes\BSTNode|null if null takes the root.
228
     * @return DataStructures\Trees\Nodes\BSTNode|null the minimum node or
229
     *  null if the tree is empty.
230
     */
231 View Code Duplication
    public function deleteMin(BinaryNodeInterface $node = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
232
        $node = $this->getMinNode($node ?? $this->root);
233
        if($node !== null) {
234
            $this->_delete($node);
235
        }
236
        
237
        return $node;
238
    }
239
    
240
    /**
241
     * Deletes the node with the maximum key and returns it. The most right and more bottom.
242
     * 
243
     * @param DataStructures\Trees\Nodes\BSTNode|null if null takes the root.
244
     * @return DataStructures\Trees\Nodes\BSTNode|null the maximum node or
245
     *  null if the tree is empty.
246
     */
247 View Code Duplication
    public function deleteMax(BinaryNodeInterface $node = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
248
        $node = $this->getMaxNode($node ?? $this->root);
249
        if($node !== null) {
250
            $this->_delete($node);
251
        }
252
253
        return $node;
254
    }
255
256
    /**
257
     * Deletes the selected node if is not null and returns the node
258
     * that replaces the deleted node. Also decrease the size of tree.
259
     *
260
     * @param DataStructures\Trees\Nodes\BSTNode|null The node to be deleted.
261
     * @return the node that replaces the deleted.
262
     */
263
    protected abstract function _delete(BinaryNodeInterface &$node);
0 ignored issues
show
Coding Style introduced by
The abstract declaration must precede the visibility declaration
Loading history...
264
265
    /**
266
     * Replaces the node n to remove a new one k and links k with the parent
267
     * of n.
268
     *
269
     * @param DataStructures\Trees\Nodes\BSTNode $nodeToReplace the node to remove.
270
     * @param DataStructures\Trees\Nodes\BSTNode|null $newNode the newNode
271
     *  to link with the $nodeToReplace parent.
272
     * @return DataStructures\Trees\Nodes\BSTNode the new linked node.
273
     */
274
    protected function replace(&$nodeToReplace, &$newNode) {
275
        if($nodeToReplace->parent === null) {
276
            $this->root = &$newNode;
277
        } else if($nodeToReplace === $nodeToReplace->parent->left) {
278
            $nodeToReplace->parent->left = &$newNode;
279
        } else if($nodeToReplace === $nodeToReplace->parent->right) {
280
            $nodeToReplace->parent->right = &$newNode;
281
        }
282
283
        if($newNode !== null) {
284
            $newNode->parent = &$nodeToReplace->parent;
285
        }
286
287
        return $newNode;
288
    }
289
290
    public function delete($key){}
291
292
    /**
293
     * Retrieves the node with the specified key.
294
     *
295
     * @param int|string $key the key used to store.
296
     * @return DataStructures\Trees\Nodes\BSTNode|null the node or null.
297
     */
298
    public function search($key) {
299
        if($this->root === null) {
300
            return null;
301
        }
302
303
        if($this->root->key === $key) {
304
            return $this->root;
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->root; of type DataStructures\Trees\Nod...res\Trees\Nodes\BSTNode adds the type DataStructures\Trees\Nodes\BSTNode to the return on line 304 which is incompatible with the return type documented by DataStructures\Trees\BinaryTreeAbstract::search of type DataStructures\Trees\Dat...rees\Nodes\BSTNode|null.
Loading history...
305
        } else {
306
            $node = $this->root;
307
            while($node !== null) {
308
                if($key < $node->key) {
309
                    $node = $node->left;
310
                } else if($key > $node->key) {
311
                    $node = $node->right;
312
                } else {
313
                    return $node;
314
                }
315
            }
316
        }
317
318
        return null;
319
    }
320
    
321
    /**
322
     * Returns true if is leaf the node.
323
     *
324
     * @param DataStructures\Trees\Nodes\BSTNode|null $node default to null.
325
     * @return true if is leaf the node, is not null and their subtrees has no
326
     *  pointers to successors.
327
     */
328
    public function isLeaf($node) { // BinaryTreeNode
329
        return ($node !== null && $node->left === null && $node->right === null);
330
    }
331
332
    /**
333
     * Checks if a node is root. New nodes that does not point to any other node
334
     * also are called a root node.
335
     *
336
     * @param DataStructures\Trees\Nodes\BSTNode|null $node default to null.
337
     * @return true if is root the node, is not null and their subtrees has no
338
     *  pointers to successors.
339
     */
340
    public function isRoot($node) {
341
        return $node !== null && $node->parent === null;
342
    }
343
344
    /**
345
     * Traverse in preorder. This is: first visit the root, then
346
     * the left subtree and finally the right subtree.
347
     *
348
     * @param Callable|null $callback the callback function to apply to each
349
     *  node.
350
     */
351
    public function preorder(Callable $callback = null) {
352
        $this->_preorder($this->root, $callback);
353
    }
354
355
    /**
356
     * Private preorder traverse method that is recursive and is called by
357
     * the public preorder method.
358
     *
359
     * @param DataStructures\Trees\Nodes\BSTNode|null $node.
0 ignored issues
show
Bug introduced by
There is no parameter named $node.. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
360
     * @param Callable|null $callback the callback function to apply to each
361
     *  node.
362
     */
363 View Code Duplication
    private function _preorder($node, Callable $callback = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
364
        if($node === null) {
365
            return;
366
        }
367
        if($callback !== null) {
368
            call_user_func($callback, $node);
369
        }
370
        $this->_preorder($node->left, $callback);
371
        $this->_preorder($node->right, $callback);
372
    }
373
374
    /**
375
     * Traverse in inorder. This is: first visit the left subtree,
376
     * then the root and finally the right subtree.
377
     *
378
     * @param Callable|null $callback the callback function to apply to each
379
     *  node.
380
     */
381
    public function inorder(Callable $callback = null) {
0 ignored issues
show
Unused Code introduced by
The parameter $callback is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
382
        $this->_inorder($this->root);
383
    }
384
385
    /**
386
     * Private inorder traverse method that is recursive and is called by
387
     * the public inorder method.
388
     *
389
     * @param DataStructures\Trees\Nodes\BSTNode|null $node.
0 ignored issues
show
Bug introduced by
There is no parameter named $node.. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
390
     * @param Callable|null $callback the callback function to apply to each
391
     *  node.
392
     */
393 View Code Duplication
    private function _inorder($node, Callable $callback = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
394
        if($node === null) {
395
            return;
396
        }
397
398
        $this->_inorder($node->left, $callback);
399
        if($callback !== null) {
400
            call_user_func($callback, $node);
401
        }
402
        $this->_inorder($node->right, $callback);
403
    }
404
405
    /**
406
     * Traverse in postorder. This is: first visit the left subtree,
407
     * then the right subtree and finally the root.
408
     *
409
     * @param Callable|null $callback the callback function to apply to each
410
     *  node.
411
     */
412
    public function postorder(Callable $callback = null) {
413
        $this->_postorder($this->root, $callback);
414
    }
415
416
    /**
417
     * Private postorder traverse method that is recursive and is called by
418
     * the public postorder method.
419
     *
420
     * @param DataStructures\Trees\Nodes\BSTNode|null $node.
0 ignored issues
show
Bug introduced by
There is no parameter named $node.. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
421
     * @param Callable|null $callback the callback function to apply to each
422
     *  node.
423
     */
424 View Code Duplication
    private function _postorder($node, Callable $callback = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
425
        if($node === null) {
426
            return;
427
        }
428
        $this->_postorder($node->left, $callback);
429
        $this->_postorder($node->right, $callback);
430
        if($callback !== null) {
431
            call_user_func($callback, $node);
432
        }
433
    }
434
435
    /**
436
     * Binds to count() method. This is equal to make $this->tree->size().
437
     *
438
     * @return integer the tree size. 0 if it is empty.
439
     */
440
    public function count() {
441
        return $this->size;
442
    }
443
}