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.
The Swift base code of this exercise is empty, so you can take this code and then implement your solution:
importFoundation// Start of `Node` classclassNode{varvalue:Intvarleft:Node?varright:Node?init(_value:Int){self.value=value}funcinsert(_value:Int){ifvalue<self.value{ifletleft{left.insert(value)}else{left=Node(value)}}elseifvalue>self.value{ifletright{right.insert(value)}else{right=Node(value)}}}// Start of `lowestCommonAncestor` methodfunclowestCommonAncestor(_node1:Int,_node2:Int)->Int?{// Enter your code here}// End of `lowestCommonAncestor` method}// Start of `Tree` classclassTree{varroot:Node?funcinsert(_value:Int){ifletroot{root.insert(value)}else{root=Node(value)}}}// End of `Tree` classlettree=Tree()guardlet_=readLine(),// first line not neededlettreeNodes=readLine()?.split(separator:" ").compactMap({Int($0)}),letinputNodes=readLine()?.split(separator:" ").compactMap({Int($0)}),inputNodes.count==2else{print("ERROR: Invalid Input!")exit(-1)}treeNodes.forEach{nodeintree.insert(node)}// Result:ifletresult=tree.root?.lowestCommonAncestor(inputNodes[0],inputNodes[1]){print(result)}else{print("No LCA!")}
Dear HackerRank team, please insert that base code or yours on this exercise.
Thanks!
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Binary Search Tree : Lowest Common Ancestor
You are viewing a single comment's thread. Return to all comments →
The Swift base code of this exercise is empty, so you can take this code and then implement your solution:
Dear HackerRank team, please insert that base code or yours on this exercise.
Thanks!