breadth first search - Python list unexpected behavior? -
when trying breadth first solution, came across unexpected behavior. in function levelorder if left node being processed first, giving correct result 3 2 5 1 4 7 , if right node kept before left node output 3 5 2 7 4 1.
i have no clue causing such behavior. question has been asked on hackerrank
given input
3 / \ 2 5 / \ \ 1 4 7
my code
import sys class node: def __init__(self,data): self.right=self.left=none self.data = data class solution: def insert(self,root,data): if root==none: return node(data) else: if data<=root.data: cur=self.insert(root.left,data) root.left=cur else: cur=self.insert(root.right,data) root.right=cur return root def levelorder(self,root): #write code here list = [] = 0 list.append(root) while < len(list): if root.left: list.append(root.left) if root.right: list.append(root.right) += 1 #print('i=',i,' len(list)=',len(list)) try: root = list[i] except exception e: = len(list) each in list: print(each.data, end=' ') t=int(input()) mytree=solution() root=none in range(t): data=int(input()) root=mytree.insert(root,data) mytree.levelorder(root)
you have given youself explanation. if go right left, every level in reverse. 2 5 -> 5 2 , 1 4 7 -> 7 4 1.
for solution, should think queue. using first-in-first-out, can append left , right branch in each level (if not none) , take first element of list print out next level. when queue empty, you're done.
as additional point, should avoid except exception
, more specific exception, in case indexerror
. that's general coding style prevent exception handlings don't want handle (like keyboardinterrupt).
Comments
Post a Comment