forked from halfrost/LeetCode-Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path114. Flatten Binary Tree to Linked List.go
73 lines (66 loc) · 1.26 KB
/
114. Flatten Binary Tree to Linked List.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type 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 = root
for i := 1; i < len(list); i++ {
cur.Left = nil
cur.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.Right
root.Right = root.Left
root.Left = nil
for 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.Left
for p.Right != nil {
p = p.Right
}
p.Right = root.Right
root.Right = root.Left
root.Left = nil
}