Created
December 12, 2020 06:37
-
-
Save brugnara/e837d839a8772bf5a95e8a37a03e4d7f to your computer and use it in GitHub Desktop.
Loop a BST using channel in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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