Flatten Binary Tree to Linked List Solutions in Go
Number 114
Difficulty Medium
Acceptance 49.4%
Link LeetCode
Solutions
Go solution by halfrost/LeetCode-Go
package leetcodeimport ("github.com/halfrost/LeetCode-Go/structures")// TreeNode definetype TreeNode = structures.TreeNode/*** Definition for a binary tree node.* type TreeNode struct {* Val int* Left *TreeNode* Right *TreeNode* }*/// 解法一 非递归func flatten(root *TreeNode) {list, cur := []int{}, &TreeNode{}preorder(root, &list)cur = rootfor i := 1; i < len(list); i++ {cur.Left = nilcur.Right = &TreeNode{Val: list[i], Left: nil, Right: nil}cur = cur.Right}return}func preorder(root *TreeNode, output *[]int) {if root != nil {*output = append(*output, root.Val)preorder(root.Left, output)preorder(root.Right, output)}}// 解法二 递归func flatten1(root *TreeNode) {if root == nil || (root.Left == nil && root.Right == nil) {return}flatten(root.Left)flatten(root.Right)currRight := root.Rightroot.Right = root.Leftroot.Left = nilfor root.Right != nil {root = root.Right}root.Right = currRight}// 解法三 递归func flatten2(root *TreeNode) {if root == nil {return}flatten(root.Right)if root.Left == nil {return}flatten(root.Left)p := root.Leftfor p.Right != nil {p = p.Right}p.Right = root.Rightroot.Right = root.Leftroot.Left = nil}