Skip to content
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

Added binary tree in python #411

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
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
28 changes: 28 additions & 0 deletions Dynamic Programming/sub set sum/python/subSetSum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
def isSubsetSum(set,n, sum) :

# Base Cases
if (sum == 0) :
return True
if (n == 0 and sum != 0) :
return False

# If last element is greater than
# sum, then ignore it
if (set[n - 1] > sum) :
return isSubsetSum(set, n - 1, sum)

# else, check if sum can be obtained
# by any of the following
# (a) including the last element
# (b) excluding the last element
return isSubsetSum(set, n-1, sum) or isSubsetSum(set, n-1, sum-set[n-1])


# Test case
set = [3, 34, 4, 12, 5, 2]
sum = 100
n = len(set)
if (isSubsetSum(set, n, sum) == True) :
print("Found a subset with given sum")
else :
print("No subset with given sum")
64 changes: 64 additions & 0 deletions Graphs/BinaryTree/python/binaryTree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
#Class which represents a node of binary tree
class Node:
def __init__(self,key):
self.left = None
self.right = None
self.val = key

#Function which add a key to binary tree
def insert(root,node):
if root is None:
root = node
else:
if root.val < node.val:
if root.right is None:
root.right = node
else:
insert(root.right, node)
else:
if root.left is None:
root.left = node
else:
insert(root.left, node)
#Function to do inorder tree traversal
def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)

#Function for searching a key in the tree
def search(root,key):

# Base Cases: root is null or key is present at root
if root is None:
return False
elif root.val == key:
return True

# Key is greater than root's key
if root.val < key:
return search(root.right,key)

# Key is smaller than root's key
return search(root.left,key)


#Test case

r = Node(50)
insert(r,Node(30))
insert(r,Node(20))
insert(r,Node(40))
insert(r,Node(70))
insert(r,Node(60))
insert(r,Node(80))

print "Result of traversing"
inorder(r)


print "Is 25 in the tree?", search(r,25)
print "Is 30 in the tree?", search(r,30)
print "Is 2 in the tree?", search(r,2)