ComputerScience220,S12023
ComputerScience220,S12023
Assignment4(traversalandoptimisation)
SeeCanvasforduedates
ThisassignmentrequiresyoutosubmitprogramsinPythonthatyouhavewrittenyourself
totheautomarker,https://www.automarker.cs.auckland.ac.nz.Yourimplementation
mustbefrom rstprinciplesandcannotuseanexistinglibrarymethodsthatmightsolve
theproblem(egperformsgraphoperationsetc).
The automarker runs onaLinuxbox. Read the automarker helpandFAQformore
details.
PleasesubmitonlyPythonsourcecode(.pyextensionsonly).
1.Arithmetictrees30marks
Youaregivenaninput lewithmultiplepairsof input lines. The rst lineofeach
pair is a tree givenas apredecessor array. The second line is the value at the
correspondingnode. Valuesat leafnodes(nodeswithnochildren)are integers. At
non-leafnodes, thetwopossiblevaluesare+or .
Thetreerepresentsanarithmeticexpressionwherethevalueatanon-leafnodeuis
thesumofvaluesatthechildrenofuinthecaseof+,ortheproductofvaluesat
thechildrenofuinthecaseof .
Youneedtocalculatethevalueateachnodeandoutputthecalculatedvalueatthe
root.Thetreeisnotconstrainedtobebinary.
Input format: Input consistsofmpairsof linesof commaseparatedvalues, so
2mlines intotal. The rst line iseachpair isacommaseparated listof integers
representingatreeinpredecessorarrayformatwhere 1representsnull.
Thesecondlineineachpairisacommaseparatedlistof integersandthesymbols+
and .Theithitemonthelist isthevalueoroperatorattheithnodeinthetree.
Forexample:-1,0,0,0,1,1
+,,2,3,0,7
2,0,-1,0
+,3,,3
Output format: For eachpairof input lines, outputa linecontainingthevalue
calculatedattherootofthetree.
Fortheexampleinputabove,outputwouldbe:
5
6