Skip to content

Commit 5d2eb02

Browse files
authored
added same tree q. no. 100 (#367)
1 parent d838d01 commit 5d2eb02

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

Python/same_tree.py

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# LEETCODE PROBLEM NO. 100 - SAME TREE
2+
3+
# In this problem, we will check if given two trees are same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
4+
5+
# we will use check if the nodes of given trees are equal or not. if they are, we will further check it's left and right child recursively for the same. if any node is different then we will return false, else True
6+
7+
# ANSWER STARTS FROM HERE =
8+
9+
# Definition for a binary tree node.
10+
# class TreeNode:
11+
# def __init__(self, val=0, left=None, right=None):
12+
# self.val = val
13+
# self.left = left
14+
# self.right = right
15+
class Solution:
16+
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
17+
if not p and not q: #return true if both nodes are Null
18+
return True
19+
if not p or not q or p.val != q.val: #return false if any of the root is Null or value of both roots is not equal
20+
return False
21+
22+
return self.isSameTree(p.left , q.left) and self.isSameTree(p.right, q.right)
23+

0 commit comments

Comments
 (0)