-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJLolibrary.py
1933 lines (1585 loc) · 56 KB
/
JLolibrary.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import absolute_import, unicode_literals, division
__all__ = ['Node', 'tree', 'bst', 'heap', 'build']
## 425
## 324
##
import heapq
import random
import numbers
from binarytree.exceptions import (
TreeHeightError,
NodeValueError,
NodeIndexError,
NodeTypeError,
NodeModifyError,
NodeNotFoundError,
NodeReferenceError,
)
def _is_balanced(root):
"""Return the height if the binary tree is balanced, -1 otherwise.
:param root: Root node of the binary tree.
:type root: binarytree.Node | None
:return: Height if the binary tree is balanced, -1 otherwise.
:rtype: int
"""
if root is None:
return 0
left = _is_balanced(root.left)
if left < 0:
return -1
right = _is_balanced(root.right)
if right < 0:
return -1
return -1 if abs(left - right) > 1 else max(left, right) + 1
def _is_bst(root, min_value=float('-inf'), max_value=float('inf')):
"""Check if the binary tree is a BST (binary search tree).
:param root: Root node of the binary tree.
:type root: binarytree.Node | None
:param min_value: Minimum node value seen.
:type min_value: int | float
:param max_value: Maximum node value seen.
:type max_value: int | float
:return: True if the binary tree is a BST, False otherwise.
:rtype: bool
"""
if root is None:
return True
return (
min_value < root.value < max_value and
_is_bst(root.left, min_value, root.value) and
_is_bst(root.right, root.value, max_value)
)
def _validate_tree_height(height):
"""Check if the height of the binary tree is valid.
:param height: Height of the binary tree (must be 0 - 9 inclusive).
:type height: int
:raise binarytree.exceptions.TreeHeightError: If height is invalid.
"""
if not (isinstance(height, int) and 0 <= height <= 9):
raise TreeHeightError('height must be an int between 0 - 9')
def _generate_perfect_bst(height):
"""Generate a perfect BST (binary search tree) and return its root.
:param height: Height of the BST.
:type height: int
:return: Root node of the BST.
:rtype: binarytree.Node
"""
max_node_count = 2 ** (height + 1) - 1
node_values = list(range(max_node_count))
return _build_bst_from_sorted_values(node_values)
def _build_bst_from_sorted_values(sorted_values):
"""Recursively build a perfect BST from odd number of sorted values.
:param sorted_values: Odd number of sorted values.
:type sorted_values: [int | float]
:return: Root node of the BST.
:rtype: binarytree.Node
"""
if len(sorted_values) == 0:
return None
mid_index = len(sorted_values) // 2
root = Node(sorted_values[mid_index])
root.left = _build_bst_from_sorted_values(sorted_values[:mid_index])
root.right = _build_bst_from_sorted_values(sorted_values[mid_index + 1:])
return root
def _generate_random_leaf_count(height):
"""Return a random leaf count for building binary trees.
:param height: Height of the binary tree.
:type height: int
:return: Random leaf count.
:rtype: int
"""
max_leaf_count = 2 ** height
half_leaf_count = max_leaf_count // 2
# A very naive way of mimicking normal distribution
roll_1 = random.randint(0, half_leaf_count)
roll_2 = random.randint(0, max_leaf_count - half_leaf_count)
return roll_1 + roll_2 or half_leaf_count
def _generate_random_node_values(height):
"""Return random node values for building binary trees.
:param height: Height of the binary tree.
:type height: int
:return: Randomly generated node values.
:rtype: [int]
"""
max_node_count = 2 ** (height + 1) - 1
node_values = list(range(max_node_count))
random.shuffle(node_values)
return node_values
def _build_tree_string(root, curr_index, index=False, delimiter='-'):
"""Recursively walk down the binary tree and build a pretty-print string.
In each recursive call, a "box" of characters visually representing the
current (sub)tree is constructed line by line. Each line is padded with
whitespaces to ensure all lines in the box have the same length. Then the
box, its width, and start-end positions of its root node value repr string
(required for drawing branches) are sent up to the parent call. The parent
call then combines its left and right sub-boxes to build a larger box etc.
:param root: Root node of the binary tree.
:type root: binarytree.Node | None
:param curr_index: Level-order_ index of the current node (root node is 0).
:type curr_index: int
:param index: If set to True, include the level-order_ node indexes using
the following format: ``{index}{delimiter}{value}`` (default: False).
:type index: bool
:param delimiter: Delimiter character between the node index and the node
value (default: '-').
:type delimiter:
:return: Box of characters visually representing the current subtree, width
of the box, and start-end positions of the repr string of the new root
node value.
:rtype: ([str], int, int, int)
.. _Level-order:
https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search
"""
if root is None:
return [], 0, 0, 0
line1 = []
line2 = []
if index:
node_repr = '{}{}{}'.format(curr_index, delimiter, root.value)
else:
node_repr = str(root.value)
new_root_width = gap_size = len(node_repr)
# Get the left and right sub-boxes, their widths, and root repr positions
l_box, l_box_width, l_root_start, l_root_end = \
_build_tree_string(root.left, 2 * curr_index + 1, index, delimiter)
r_box, r_box_width, r_root_start, r_root_end = \
_build_tree_string(root.right, 2 * curr_index + 2, index, delimiter)
# Draw the branch connecting the current root node to the left sub-box
# Pad the line with whitespaces where necessary
if l_box_width > 0:
l_root = (l_root_start + l_root_end) // 2 + 1
line1.append(' ' * (l_root + 1))
line1.append('_' * (l_box_width - l_root))
line2.append(' ' * l_root + '/')
line2.append(' ' * (l_box_width - l_root))
new_root_start = l_box_width + 1
gap_size += 1
else:
new_root_start = 0
# Draw the representation of the current root node
line1.append(node_repr)
line2.append(' ' * new_root_width)
# Draw the branch connecting the current root node to the right sub-box
# Pad the line with whitespaces where necessary
if r_box_width > 0:
r_root = (r_root_start + r_root_end) // 2
line1.append('_' * r_root)
line1.append(' ' * (r_box_width - r_root + 1))
line2.append(' ' * r_root + '\\')
line2.append(' ' * (r_box_width - r_root))
gap_size += 1
new_root_end = new_root_start + new_root_width - 1
# Combine the left and right sub-boxes with the branches drawn above
gap = ' ' * gap_size
new_box = [''.join(line1), ''.join(line2)]
for i in range(max(len(l_box), len(r_box))):
l_line = l_box[i] if i < len(l_box) else ' ' * l_box_width
r_line = r_box[i] if i < len(r_box) else ' ' * r_box_width
new_box.append(l_line + gap + r_line)
# Return the new box, its width and its root repr positions
return new_box, len(new_box[0]), new_root_start, new_root_end
def _get_tree_properties(root):
"""Inspect the binary tree and return its properties (e.g. height).
:param root: Root node of the binary tree.
:rtype: binarytree.Node
:return: Binary tree properties.
:rtype: dict
"""
is_descending = True
is_ascending = True
min_node_value = root.value
max_node_value = root.value
size = 0
leaf_count = 0
min_leaf_depth = 0
max_leaf_depth = -1
is_strict = True
is_complete = True
current_nodes = [root]
non_full_node_seen = False
while len(current_nodes) > 0:
max_leaf_depth += 1
next_nodes = []
for node in current_nodes:
size += 1
value = node.value
min_node_value = min(value, min_node_value)
max_node_value = max(value, max_node_value)
# Node is a leaf.
if node.left is None and node.right is None:
if min_leaf_depth == 0:
min_leaf_depth = max_leaf_depth
leaf_count += 1
if node.left is not None:
if node.left.value > value:
is_descending = False
elif node.left.value < value:
is_ascending = False
next_nodes.append(node.left)
is_complete = not non_full_node_seen
else:
non_full_node_seen = True
if node.right is not None:
if node.right.value > value:
is_descending = False
elif node.right.value < value:
is_ascending = False
next_nodes.append(node.right)
is_complete = not non_full_node_seen
else:
non_full_node_seen = True
# If we see a node with only one child, it is not strict
is_strict &= (node.left is None) == (node.right is None)
current_nodes = next_nodes
return {
'height': max_leaf_depth,
'size': size,
'is_max_heap': is_complete and is_descending,
'is_min_heap': is_complete and is_ascending,
'is_perfect': leaf_count == 2 ** max_leaf_depth,
'is_strict': is_strict,
'is_complete': is_complete,
'leaf_count': leaf_count,
'min_node_value': min_node_value,
'max_node_value': max_node_value,
'min_leaf_depth': min_leaf_depth,
'max_leaf_depth': max_leaf_depth,
}
class Node(object):
"""Represents a binary tree node.
This class provides methods and properties for managing the current node
instance, and the binary tree in which the node is the root of. When a
docstring in this class mentions "binary tree", it is referring to the
current node and its descendants.
:param value: Node value (must be a number).
:type value: int | float
:param left: Left child node (default: None).
:type left: binarytree.Node | None
:param right: Right child node (default: None).
:type right: binarytree.Node | None
:raise binarytree.exceptions.NodeTypeError: If left or right child node is
not an instance of :class:`binarytree.Node`.
:raise binarytree.exceptions.NodeValueError: If node value is not a number
(e.g. int, float).
"""
def __init__(self, value, left=None, right=None):
# if not isinstance(value, numbers.Number):
# raise NodeValueError('node value must be a number')
if left is not None and not isinstance(left, Node):
raise NodeTypeError('left child must be a Node instance')
if right is not None and not isinstance(right, Node):
raise NodeTypeError('right child must be a Node instance')
self.value = value
self.left = left
self.right = right
def __repr__(self):
"""Return the string representation of the current node.
:return: String representation.
:rtype: str | unicode
**Example**:
.. doctest::
>>> from binarytree import Node
>>>
>>> Node(1)
Node(1)
"""
return 'Node({})'.format(self.value)
def __str__(self):
"""Return the pretty-print string for the binary tree.
:return: Pretty-print string.
:rtype: str | unicode
**Example**:
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1)
>>> root.left = Node(2)
>>> root.right = Node(3)
>>> root.left.right = Node(4)
>>>
>>> print(root)
<BLANKLINE>
__1
/ \\
2 3
\\
4
<BLANKLINE>
.. note::
To include level-order_ indexes in the output string, use
:func:`binarytree.Node.pprint` instead.
.. _level-order:
https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search
"""
lines = _build_tree_string(self, 0, False, '-')[0]
return '\n' + '\n'.join((line.rstrip() for line in lines))
def __setattr__(self, attr, obj):
"""Modified version of ``__setattr__`` with extra sanity checking.
Class attributes **left**, **right** and **value** are validated.
:param attr: Name of the class attribute.
:type attr: str | unicode
:param obj: Object to set.
:type obj: object
:raise binarytree.exceptions.NodeTypeError: If left or right child is
not an instance of :class:`binarytree.Node`.
:raise binarytree.exceptions.NodeValueError: If node value is not a
number (e.g. int, float).
**Example**:
.. doctest::
>>> from binarytree import Node
>>>
>>> node = Node(1)
>>> node.left = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
NodeTypeError: Left child must be a Node instance
.. doctest::
>>> from binarytree import Node
>>>
>>> node = Node(1)
>>> node.value = 'invalid' # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
NodeValueError: node value must be a number
"""
if attr == 'left':
if obj is not None and not isinstance(obj, Node):
raise NodeTypeError(
'left child must be a Node instance')
elif attr == 'right':
if obj is not None and not isinstance(obj, Node):
raise NodeTypeError(
'right child must be a Node instance')
# elif attr == 'value' and not isinstance(obj, numbers.Number):
# raise NodeValueError('node value must be a number')
object.__setattr__(self, attr, obj)
def __iter__(self):
"""Iterate through the nodes in the binary tree in level-order_.
.. _level-order:
https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search
:return: Node iterator.
:rtype: (binarytree.Node)
**Example**:
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1)
>>> root.left = Node(2)
>>> root.right = Node(3)
>>> root.left.left = Node(4)
>>> root.left.right = Node(5)
>>>
>>> print(root)
<BLANKLINE>
__1
/ \\
2 3
/ \\
4 5
<BLANKLINE>
>>> [node for node in root]
[Node(1), Node(2), Node(3), Node(4), Node(5)]
"""
current_nodes = [self]
while len(current_nodes) > 0:
next_nodes = []
for node in current_nodes:
yield node
if node.left is not None:
next_nodes.append(node.left)
if node.right is not None:
next_nodes.append(node.right)
current_nodes = next_nodes
def __len__(self):
"""Return the total number of nodes in the binary tree.
:return: Total number of nodes.
:rtype: int
**Example**:
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1)
>>> root.left = Node(2)
>>> root.right = Node(3)
>>>
>>> len(root)
3
.. note::
This method is equivalent to :attr:`binarytree.Node.size`.
"""
return self.properties['size']
def __getitem__(self, index):
"""Return the node (or subtree) at the given level-order_ index.
.. _level-order:
https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search
:param index: Level-order index of the node.
:type index: int
:return: Node (or subtree) at the given index.
:rtype: binarytree.Node
:raise binarytree.exceptions.NodeIndexError: If node index is invalid.
:raise binarytree.exceptions.NodeNotFoundError: If the node is missing.
**Example**:
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1) # index: 0, value: 1
>>> root.left = Node(2) # index: 1, value: 2
>>> root.right = Node(3) # index: 2, value: 3
>>>
>>> root[0]
Node(1)
>>> root[1]
Node(2)
>>> root[2]
Node(3)
>>> root[3] # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
NodeNotFoundError: node missing at index 3
"""
if not isinstance(index, int) or index < 0:
raise NodeIndexError(
'node index must be a non-negative int')
current_nodes = [self]
current_index = 0
has_more_nodes = True
while has_more_nodes:
has_more_nodes = False
next_nodes = []
for node in current_nodes:
if current_index == index:
if node is None:
break
else:
return node
current_index += 1
if node is None:
next_nodes.extend((None, None))
continue
next_nodes.extend((node.left, node.right))
if node.left is not None or node.right is not None:
has_more_nodes = True
current_nodes = next_nodes
raise NodeNotFoundError('node missing at index {}'.format(index))
def __setitem__(self, index, node):
"""Insert a node (or subtree) at the given level-order_ index.
* An exception is raised if the parent node is missing.
* Any existing node or subtree is overwritten.
* Root node (current node) cannot be replaced.
.. _level-order:
https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search
:param index: Level-order index of the node.
:type index: int
:param node: Node to insert.
:type node: binarytree.Node
:raise binarytree.exceptions.NodeTypeError: If new node is not an
instance of :class:`binarytree.Node`.
:raise binarytree.exceptions.NodeNotFoundError: If parent is missing.
:raise binarytree.exceptions.NodeModifyError: If user attempts to
overwrite the root node (current node).
**Example**:
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1) # index: 0, value: 1
>>> root.left = Node(2) # index: 1, value: 2
>>> root.right = Node(3) # index: 2, value: 3
>>>
>>> root[0] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
NodeModifyError: cannot modify the root node
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1) # index: 0, value: 1
>>> root.left = Node(2) # index: 1, value: 2
>>> root.right = Node(3) # index: 2, value: 3
>>>
>>> root[11] = Node(4) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
NodeNotFoundError: parent node missing at index 5
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1) # index: 0, value: 1
>>> root.left = Node(2) # index: 1, value: 2
>>> root.right = Node(3) # index: 2, value: 3
>>>
>>> root[1] = Node(4)
>>>
>>> root.left
Node(4)
"""
if index == 0:
raise NodeModifyError('cannot modify the root node')
parent_index = (index - 1) // 2
try:
parent = self.__getitem__(parent_index)
except NodeNotFoundError:
raise NodeNotFoundError(
'parent node missing at index {}'.format(parent_index))
setattr(parent, 'left' if index % 2 else 'right', node)
def __delitem__(self, index):
"""Remove the node (or subtree) at the given level-order_ index.
* An exception is raised if the target node is missing.
* The descendants of the target node (if any) are also removed.
* Root node (current node) cannot be deleted.
.. _level-order:
https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search
:param index: Level-order index of the node.
:type index: int
:raise binarytree.exceptions.NodeNotFoundError: If the target node or
its parent is missing.
:raise binarytree.exceptions.NodeModifyError: If user attempts to
delete the root node (current node).
**Example**:
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1) # index: 0, value: 1
>>> root.left = Node(2) # index: 1, value: 2
>>> root.right = Node(3) # index: 2, value: 3
>>>
>>> del root[0] # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
NodeModifyError: cannot delete the root node
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1) # index: 0, value: 1
>>> root.left = Node(2) # index: 1, value: 2
>>> root.right = Node(3) # index: 2, value: 3
>>>
>>> del root[2]
>>>
>>> root[2] # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
NodeNotFoundError: node missing at index 2
"""
if index == 0:
raise NodeModifyError('cannot delete the root node')
parent_index = (index - 1) // 2
try:
parent = self.__getitem__(parent_index)
except NodeNotFoundError:
raise NodeNotFoundError(
'no node to delete at index {}'.format(index))
child_attr = 'left' if index % 2 == 1 else 'right'
if getattr(parent, child_attr) is None:
raise NodeNotFoundError(
'no node to delete at index {}'.format(index))
setattr(parent, child_attr, None)
def pprint(self, index=False, delimiter='-'):
"""Pretty-print the binary tree.
:param index: If set to True (default: False), display level-order_
indexes using the format: ``{index}{delimiter}{value}``.
:type index: bool
:param delimiter: Delimiter character between the node index and
the node value (default: '-').
:type delimiter: str | unicode
**Example**:
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1) # index: 0, value: 1
>>> root.left = Node(2) # index: 1, value: 2
>>> root.right = Node(3) # index: 2, value: 3
>>> root.left.right = Node(4) # index: 4, value: 4
>>>
>>> root.pprint()
<BLANKLINE>
__1
/ \\
2 3
\\
4
<BLANKLINE>
>>> root.pprint(index=True) # Format: {index}-{value}
<BLANKLINE>
_____0-1_
/ \\
1-2_ 2-3
\\
4-4
<BLANKLINE>
.. note::
If you do not need level-order_ indexes in the output string, use
:func:`binarytree.Node.__str__` instead.
.. _level-order:
https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search
"""
lines = _build_tree_string(self, 0, index, delimiter)[0]
print('\n' + '\n'.join((line.rstrip() for line in lines)))
def validate(self):
"""Check if the binary tree is malformed.
:raise binarytree.exceptions.NodeReferenceError: If there is a
cyclic reference to a node in the binary tree.
:raise binarytree.exceptions.NodeTypeError: If a node is not an
instance of :class:`binarytree.Node`.
:raise binarytree.exceptions.NodeValueError: If a node value is not a
number (e.g. int, float).
**Example**:
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1)
>>> root.left = Node(2)
>>> root.right = root # Cyclic reference to root
>>>
>>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
NodeReferenceError: cyclic node reference at index 0
"""
has_more_nodes = True
visited = set()
to_visit = [self]
index = 0
while has_more_nodes:
has_more_nodes = False
next_nodes = []
for node in to_visit:
if node is None:
next_nodes.extend((None, None))
else:
if node in visited:
raise NodeReferenceError(
'cyclic node reference at index {}'.format(index))
if not isinstance(node, Node):
raise NodeTypeError(
'invalid node instance at index {}'.format(index))
if not isinstance(node.value, numbers.Number):
raise NodeValueError(
'invalid node value at index {}'.format(index))
if node.left is not None or node.right is not None:
has_more_nodes = True
visited.add(node)
next_nodes.extend((node.left, node.right))
index += 1
to_visit = next_nodes
@property
def values(self):
"""Return the `list representation`_ of the binary tree.
.. _list representation:
https://en.wikipedia.org/wiki/Binary_tree#Arrays
:return: List representation of the binary tree, which is a list of
node values in breadth-first order starting from the root (current
node). If a node is at index i, its left child is always at 2i + 1,
right child at 2i + 2, and parent at index floor((i - 1) / 2). None
indicates absence of a node at that index. See example below for an
illustration.
:rtype: [int | float | None]
**Example**:
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1)
>>> root.left = Node(2)
>>> root.right = Node(3)
>>> root.left.right = Node(4)
>>>
>>> root.values
[1, 2, 3, None, 4]
"""
current_nodes = [self]
has_more_nodes = True
values = []
while has_more_nodes:
has_more_nodes = False
next_nodes = []
for node in current_nodes:
if node is None:
values.append(None)
next_nodes.extend((None, None))
continue
if node.left is not None or node.right is not None:
has_more_nodes = True
values.append(node.value)
next_nodes.extend((node.left, node.right))
current_nodes = next_nodes
# Get rid of trailing None's
while values and values[-1] is None:
values.pop()
return values
@property
def leaves(self):
"""Return the leaf nodes of the binary tree.
A leaf node is any node that does not have child nodes.
:return: List of leaf nodes.
:rtype: [binarytree.Node]
**Example**:
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1)
>>> root.left = Node(2)
>>> root.right = Node(3)
>>> root.left.right = Node(4)
>>>
>>> print(root)
<BLANKLINE>
__1
/ \\
2 3
\\
4
<BLANKLINE>
>>> root.leaves
[Node(3), Node(4)]
"""
current_nodes = [self]
leaves = []
while len(current_nodes) > 0:
next_nodes = []
for node in current_nodes:
if node.left is None and node.right is None:
leaves.append(node)
continue
if node.left is not None:
next_nodes.append(node.left)
if node.right is not None:
next_nodes.append(node.right)
current_nodes = next_nodes
return leaves
@property
def levels(self):
"""Return the nodes in the binary tree level by level.
:return: Lists of nodes level by level.
:rtype: [[binarytree.Node]]
**Example**:
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1)
>>> root.left = Node(2)
>>> root.right = Node(3)
>>> root.left.right = Node(4)
>>>
>>> print(root)
<BLANKLINE>
__1
/ \\
2 3
\\
4
<BLANKLINE>
>>>
>>> root.levels
[[Node(1)], [Node(2), Node(3)], [Node(4)]]
"""
current_nodes = [self]
levels = []
while len(current_nodes) > 0:
next_nodes = []
for node in current_nodes:
if node.left is not None:
next_nodes.append(node.left)
if node.right is not None:
next_nodes.append(node.right)
levels.append(current_nodes)
current_nodes = next_nodes
return levels
@property
def height(self):
"""Return the height of the binary tree.
Height of a binary tree is the number of edges on the longest path
between the root node and a leaf node. Binary tree with just a single
node has a height of 0.
:return: Height of the binary tree.
:rtype: int
**Example**:
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1)
>>> root.left = Node(2)
>>> root.left.left = Node(3)
>>>
>>> print(root)
<BLANKLINE>
1
/
2
/
3
<BLANKLINE>
>>> root.height
2
.. note::
A binary tree with only a root node has a height of 0.
"""
return _get_tree_properties(self)['height']
@property
def size(self):
"""Return the total number of nodes in the binary tree.
:return: Total number of nodes.
:rtype: int
**Example**:
.. doctest::