We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
an in order traversal of the tree and save the order indexes into data_list
set new property ancestor into node objects, which is somewhat cheating because may only be add in dynamic language such as Python, but can also be implement in other static languages by using data structure like dictionaries / hashmaps
check data_list is in order, and also no duplication (by checking length)
fromcollectionsimportdefaultdictdefcheckBST(root):node_traversed_counts=defaultdict(int)current_node=rootcurrent_node.ancestor=Nonedata_list=[]whilenode_traversed_counts[root]<3:# new nodeifnotnode_traversed_counts.get(current_node):node_traversed_counts[current_node]+=1# is leaf nodeifnotcurrent_node.leftandnotcurrent_node.right:data_list.append(current_node.data)current_node=current_node.ancestor# is not leaf nodeelse:ifcurrent_node.left:current_node.left.ancestor=current_nodecurrent_node=current_node.left# node having been traversed beforeelse:node_traversed_counts[current_node]+=1ifnode_traversed_counts[current_node]==2:data_list.append(current_node.data)ifcurrent_node.right:current_node.right.ancestor=current_nodecurrent_node=current_node.rightcontinuecurrent_node=current_node.ancestorreturndata_list==sorted(data_list)andlen(set(data_list))==len(data_list)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Trees: Is This a Binary Search Tree?
You are viewing a single comment's thread. Return to all comments →
data_list
ancestor
into node objects, which is somewhat cheating because may only be add in dynamic language such as Python, but can also be implement in other static languages by using data structure like dictionaries / hashmapsdata_list
is in order, and also no duplication (by checking length)