Skip to content

Instantly share code, notes, and snippets.

@alldroll
Created February 13, 2020 08:54
Show Gist options
  • Select an option

  • Save alldroll/e1b8e14b613cde351409824360c80b15 to your computer and use it in GitHub Desktop.

Select an option

Save alldroll/e1b8e14b613cde351409824360c80b15 to your computer and use it in GitHub Desktop.
// https://leetcode.com/problems/flatten-binary-tree-to-linked-list
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func flatten(root *TreeNode) {
ch := make(chan *TreeNode)
go func () {
preOrderTraverse(root, ch)
close(ch)
}()
var prev *TreeNode
for curr := range ch {
curr.Right = prev
curr.Left = nil
prev = curr
}
}
func preOrderTraverse(root *TreeNode, ch chan *TreeNode) {
if root == nil {
return
}
preOrderTraverse(root.Right, ch)
preOrderTraverse(root.Left, ch)
ch <- root
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment