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.
golang solution Tree construction O(n log n) Tree Trasversal Print O(n)
packagemainimport("bufio""fmt""io""os""strconv""strings")typeNodestruct{ValueintLeft*NodeRight*Node}funcprintTree(node*Node){fmt.Printf("%d ",node.Value)ifnode.Left!=nil{printTree(node.Left)}ifnode.Right!=nil{printTree(node.Right)}}funcinsertNode(node*Node,valueint){ifnode.Value>value{ifnode.Left==nil{node.Left=&Node{Value:value,}return}insertNode(node.Left,value)}else{ifnode.Right==nil{node.Right=&Node{Value:value,}return}insertNode(node.Right,value)}}funccontructTree(nodes[]int)*Node{// 1 <= nodes in the tree root:=&Node{Value:nodes[0],}fori:=1;i<len(nodes);i++{insertNode(root,nodes[i])}returnroot}funcmain(){reader:=bufio.NewReaderSize(os.Stdin,16*1024*1024)readLine(reader)input:=strings.TrimSpace(readLine(reader))stringNodes:=strings.Split(input," ")nodes:=make([]int,len(stringNodes))fori,node:=rangestringNodes{nodes[i],_=strconv.Atoi(node)}root:=contructTree(nodes)printTree(root)}funcreadLine(reader*bufio.Reader)string{str,_,err:=reader.ReadLine()iferr==io.EOF{return""}returnstrings.TrimRight(string(str),"\r\n")}funccheckError(errerror){iferr!=nil{panic(err)}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Tree: Preorder Traversal
You are viewing a single comment's thread. Return to all comments →
golang solution Tree construction O(n log n) Tree Trasversal Print O(n)