-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathidentical_binary_trees.py
79 lines (74 loc) · 1.58 KB
/
identical_binary_trees.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
# -----------------------------------------------
# Author : Mohit Chaudhari
# Created Date : 23/09/21
# -----------------------------------------------
# ***** Identical Binary Trees *****
# Problem Description
#
# Given two binary trees, check if they are equal or not.
#
# Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
#
#
#
# Problem Constraints
# 1 <= number of nodes <= 105
#
#
#
# Input Format
# First argument is a root node of first tree, A.
#
# Second argument is a root node of second tree, B.
#
#
#
# Output Format
# Return 0 / 1 ( 0 for false, 1 for true ) for this problem.
#
#
#
# Example Input
# Input 1:
#
# 1 1
# / \ / \
# 2 3 2 3
# Input 2:
#
# 1 1
# / \ / \
# 2 3 3 3
#
#
# Example Output
# Output 1:
#
# 1
# Output 2:
#
# 0
#
#
# Example Explanation
# Explanation 1:
#
# Both trees are structurally identical and the nodes have the same value.
# Explanation 2:
#
# Value of left child of the tree is different.
class Solution:
# @param A : root node of tree
# @param B : root node of tree
# @return an integer
def isSameTree(self, a, b):
# 1. Both empty
if a is None and b is None:
return 1
# 2. Both non-empty -> Compare them
if a is not None and b is not None:
return 1 if bool(((a.val == b.val) and
self.isSameTree(a.left, b.left) and
self.isSameTree(a.right, b.right))) else 0
# 3. one empty, one not -- false
return 0