Write Code to Determine if Two Trees are Identical | A binary tree node has data , pointer to left child and a pointer to right child ; Given two trees , return true if they are structurally identical ; 1. Both empty ; 2. Both non - empty -> Compare them ; 3. one empty , one not -- false ; Driver program to test identicalTress function
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def identicalTrees ( a , b ) : NEW_LINE INDENT if a is None and b is None : NEW_LINE INDENT return True NEW_LINE DEDENT if a is not None and b is not None : NEW_LINE INDENT return ( ( a . data == b . data ) and identicalTrees ( a . left , b . left ) and identicalTrees ( a . right , b . right ) ) NEW_LINE DEDENT return False NEW_LINE DEDENT root1 = Node ( 1 ) NEW_LINE root2 = Node ( 1 ) NEW_LINE root1 . left = Node ( 2 ) NEW_LINE root1 . right = Node ( 3 ) NEW_LINE root1 . left . left = Node ( 4 ) NEW_LINE root1 . left . right = Node ( 5 ) NEW_LINE root2 . left = Node ( 2 ) NEW_LINE root2 . right = Node ( 3 ) NEW_LINE root2 . left . left = Node ( 4 ) NEW_LINE root2 . left . right = Node ( 5 ) NEW_LINE if identicalTrees ( root1 , root2 ) : NEW_LINE INDENT print " Both ▁ trees ▁ are ▁ identical " NEW_LINE DEDENT else : NEW_LINE INDENT print " Trees ▁ are ▁ not ▁ identical " NEW_LINE DEDENT