Created
February 13, 2020 08:54
-
-
Save alldroll/e1b8e14b613cde351409824360c80b15 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // 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