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

Adding solution to the problem of if 2 binary trees are symmetric or not.Please merge my solution as part of Hacktoberfest 2024. #2043

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
51 changes: 51 additions & 0 deletions DS&Algo Programs in Python/SymmetricTree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
class BinaryTree:
def __init__(self,data):
self.data=data
self.left=None
self.right=None

def treeinput():
data=int(input())
if data==-1:
return None
root=BinaryTree(data)
leftdata=treeinput()
rightdata=treeinput()
root.left=leftdata
root.right=rightdata
return root

def printTree(root):
if root==None:
return
print(root.data,end=":")
if root.left!=None:
print("L",root.left.data,end=",")
if root.right!=None:
print("R",root.right.data,end="")
print()
printTree(root.left)
printTree(root.right)

def isSymmetric(root):
if not root:
return True
def check(left,right):

if not left and not right:
return True

if not left or not right:
return False

return (left.data==right.data and check(left.left,right.right) and check(left.right,right.left))


return check(root.left,root.right)

root=treeinput()
printTree(root)
if isSymmetric(root):
print("THE TREE IS SYMMETRIC")
else:
print("THE TREE IS NOT SYMMETRIC")