Skip to content

[WIP] Added binary tree traversals #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 28, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
in-order, pre-order code
  • Loading branch information
czgdp1807 committed Jun 27, 2019
commit f896c9c76a70ced677e80eadbcfe65a7fe9404eb
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ __pycache__/
.pytest_cache/
pre_commit.ps1
.coverage
# for developement purposes
pds_debug.py
18 changes: 17 additions & 1 deletion pydatastructs/miscellaneous_data_structures/stack.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def __new__(cls, implementation='array', **kwargs):
if implementation == 'array':
return ArrayStack(
kwargs.get('maxsize', None),
kwargs.get('top', None),
kwargs.get('top', 0),
kwargs.get('items', None),
kwargs.get('dtype', int))
raise NotImplementedError(
Expand All @@ -74,6 +74,14 @@ def pop(self, *args, **kwargs):
raise NotImplementedError(
"This is an abstract method.")

@property
def is_empty(self):
return None

@property
def peek(self):
return None

class ArrayStack(Stack):

def __new__(cls, maxsize=None, top=0, items=None, dtype=int):
Expand Down Expand Up @@ -107,6 +115,14 @@ def pop(self):
self.items[self.top] = None
return r

@property
def is_empty(self):
return self.top == 0

@property
def peek(self):
return self.items[self.top - 1]

def __str__(self):
"""
Used for printing.
Expand Down
2 changes: 1 addition & 1 deletion pydatastructs/trees/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
)

from .binary_trees import (
Node, BinaryTree, BinarySearchTree
Node, BinaryTree, BinarySearchTree, BinaryTreeTraversal
)
__all__.extend(binary_trees.__all__)

Expand Down
90 changes: 89 additions & 1 deletion pydatastructs/trees/binary_trees.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from __future__ import print_function, division
from pydatastructs.utils import Node
from pydatastructs.miscellaneous_data_structures import Stack

__all__ = [
'Node',
'BinaryTree',
'BinarySearchTree'
'BinarySearchTree',
'BinaryTreeTraversal'
]

class BinaryTree(object):
Expand Down Expand Up @@ -243,3 +245,89 @@ def delete(self, key):
self.tree[parent].right = child

return True

class BinaryTreeTraversal(object):

__slots__ = ['tree']

def __new__(cls, tree):
if not isinstance(tree, BinaryTree):
raise TypeError("%s is not a binary tree"%(tree))
obj = object.__new__(cls)
obj.tree = tree
return obj

def _pre_order(self, node):
visit = []
if node == None:
return visit
tree, size = self.tree.tree, self.tree.size
s = Stack(maxsize=size)
s.push(node)
while not s.is_empty:
node = s.pop()
visit.append(tree[node])
if tree[node].right != None:
s.push(tree[node].right)
if tree[node].left != None:
s.push(tree[node].left)
return visit

def _in_order(self, node):
visit = []
tree, size = self.tree.tree, self.tree.size
s = Stack(maxsize=size)
while not s.is_empty or node != None:
if node != None:
s.push(node)
node = tree[node].left
else:
node = s.pop()
visit.append(tree[node])
node = tree[node].right
return visit

def _post_order(self, node):
visit = []
tree, size = self.tree.tree, self.tree.size
s = Stack(maxsize=size)
s.push(node)
last, cache = [None, None], 0
while not s.is_empty:
node = s.peek
l, r = tree[node].left, tree[node].right
cl, cr = l == None or l in last, r == None or r in last
if cl and cr:
s.pop()
visit.append(tree[node])
last[cache] = node
cache = 1 - cache
continue
if not cr:
s.push(r)
if not cl:
s.push(l)
# last_node_visited = None
# while (not s.is_empty) or node != None:
# if node != None:
# s.push(node)
# node = tree[node].left
# else:
# peek_node = s.peek
# if tree[peek_node].right != None and \
# last_node_visited != tree[peek_node].right:
# node = tree[peek_node].right
# else:
# visit.append(tree[peek_node])
# last_node_visited = s.pop()
return visit

def depth_first_search(self, order='in_order', node=None):
if node == None:
node = self.tree.root_idx
if order not in ('in_order', 'post_order', 'pre_order', 'out_order'):
raise NotImplementedError(
"%s order is not implemented yet."
"We only support `in_order`, `post_order`, "
"`pre_order` and `out_order` traversals.")
return getattr(self, '_' + order)(node)
27 changes: 26 additions & 1 deletion pydatastructs/trees/tests/test_binary_trees.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from pydatastructs.trees.binary_trees import BinarySearchTree
from pydatastructs.trees.binary_trees import (
BinarySearchTree, BinaryTreeTraversal)
from pydatastructs.utils.raises_util import raises

def test_BinarySearchTree():
Expand Down Expand Up @@ -32,3 +33,27 @@ def test_BinarySearchTree():
bc = BST(1, 1)
assert bc.insert(1, 2) == None
raises(ValueError, lambda: BST(root_data=6))

def test_BinaryTreeTraversal():
BST = BinarySearchTree
BTT = BinaryTreeTraversal
b = BST('F', 'F')
b.insert('B', 'B')
b.insert('A', 'A')
b.insert('G', 'G')
b.insert('D', 'D')
b.insert('C', 'C')
b.insert('E', 'E')
b.insert('I', 'I')
b.insert('H', 'H')
trav = BTT(b)
pre = trav.depth_first_search(order='pre_order')
assert [str(n) for n in pre] == \
["(1, 'F', 'F', 3)", "(2, 'B', 'B', 4)", "(None, 'A', 'A', None)",
"(5, 'D', 'D', 6)", "(None, 'C', 'C', None)", "(None, 'E', 'E', None)",
"(None, 'G', 'G', 7)", "(8, 'I', 'I', None)", "(None, 'H', 'H', None)"]
post = trav.depth_first_search()
assert [str(n) for n in post] == \
["(None, 'A', 'A', None)", "(2, 'B', 'B', 4)", "(None, 'C', 'C', None)",
"(5, 'D', 'D', 6)", "(None, 'E', 'E', None)", "(1, 'F', 'F', 3)",
"(None, 'G', 'G', 7)", "(None, 'H', 'H', None)", "(8, 'I', 'I', None)"]