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.
importjava.util.ScannertraitTree{defvalue:Intdefswap(k:Int,depth:Int=1):TreedefinOrder:Seq[Tree]}objectTree{privatevalemptyValue=-1defparse(nodes:IndexedSeq[(Int,Int)]):Tree={definner(index:Int):Tree=if(index==emptyValue)Emptyelse{val(leftIndex,rightIndex)=nodes(index-1)newNode(index,inner(leftIndex),inner(rightIndex))}inner(1)}}classNode(valvalue:Int,left:Tree,right:Tree)extendsTree{overridedefswap(k:Int,depth:Int):Tree={val(l,r)=if(depth%k==0)(right,left)else(left,right)newNode(value,l.swap(k,depth+1),r.swap(k,depth+1))}overridedefinOrder:Seq[Tree]=(left.inOrder:+this)++right.inOrder}objectEmptyextendsTree{overridedefvalue:Int=thrownewException("Value of empty tree")overridedefswap(k:Int,depth:Int):Tree=thisoverridedefinOrder:Seq[Tree]=Vector()}caseclassRule(n:Int)objectSolution{defmain(args:Array[String]):Unit={valsc=newScanner(System.in)valn=sc.nextIntvalnodes=(0untiln).map(_=>(sc.nextInt,sc.nextInt))valroot=Tree.parse(nodes)valt=sc.nextIntvalswaps=(0untilt).map(_=>sc.nextInt)sc.close()swaps.foldLeft(root)((acc,query)=>{valtree=acc.swap(query)println(tree.inOrder.map(_.value).mkString(" "))tree})}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Swap Nodes
You are viewing a single comment's thread. Return to all comments →
Scala solution