Skip to content

Instantly share code, notes, and snippets.

@brugnara
Created December 12, 2020 06:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brugnara/e837d839a8772bf5a95e8a37a03e4d7f to your computer and use it in GitHub Desktop.
Save brugnara/e837d839a8772bf5a95e8a37a03e4d7f to your computer and use it in GitHub Desktop.
Loop a BST using channel in golang
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func printBST(root *TreeNode) {
chn := make(chan int)
go func(){
// remember to close the chan!
defer close(chn)
loopChn(root, chn)
}()
for n := range chn {
fmt.Println(n)
}
}
func loopChn(leaf *TreeNode, chn chan int) {
if leaf == nil {
return
}
loopChn(leaf.Left, chn)
chn <- leaf.Val
loopChn(leaf.Right, chn)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment