-
Notifications
You must be signed in to change notification settings - Fork 7
/
convert_bst.go
76 lines (72 loc) · 1.62 KB
/
convert_bst.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
74
75
76
package main
// import . "nc_tools"
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
/**
*
* @param pRootOfTree TreeNode类
* @return TreeNode类
*/
// https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5?tpId=13&tqId=11179&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking
func ConvertWithArray(pRootOfTree *TreeNode) *TreeNode {
if pRootOfTree == nil {
return nil
}
order := make([]*TreeNode, 0, 1000)
var traverse func(node *TreeNode)
// 中序遍历,得出有序列表
traverse = func(node *TreeNode) {
if node == nil {
return
}
traverse(node.Left)
order = append(order, node)
traverse(node.Right)
}
traverse(pRootOfTree)
newRoot := order[0]
newRoot.Left = nil
for i := 0; i < len(order)-1; i++ {
cur := order[i]
next := order[i+1]
cur.Right = next
next.Left = cur
next.Right = nil
}
return newRoot
}
/**
*
* @param pRootOfTree TreeNode类
* @return TreeNode类
*/
// https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5?tpId=13&tqId=11179&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking
func Convert(pRootOfTree *TreeNode) *TreeNode {
if pRootOfTree == nil {
return nil
}
var prev *TreeNode
var inOrder func(node *TreeNode)
// 中序遍历,得出有序列表
inOrder = func(node *TreeNode) {
if node == nil {
return
}
inOrder(node.Left)
node.Left = prev
if prev != nil {
prev.Right = node
}
prev = node
inOrder(node.Right)
}
inOrder(pRootOfTree)
head := pRootOfTree
for head.Left != nil {
head = head.Left
}
return head
}