-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfull_tree.go
89 lines (72 loc) · 1.31 KB
/
full_tree.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
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
/*
This problem was asked by Yahoo.
Recall that a full binary tree is one in which each node is either a
leaf node,
or has two children.
Given a binary tree,
convert it to a full one by removing nodes with only one child.
For example, given the following tree:
0
/ \
1 2
/ \
3 4
\ / \
5 6 7
You should convert it to:
0
/ \
5 4
/ \
6 7
*/
import (
"binary_tree/tree"
"fmt"
"os"
)
func main() {
drawGraph := false
stringRep := os.Args[1]
if os.Args[1] == "-g" {
drawGraph = true
stringRep = os.Args[2]
}
root := tree.CreateNumericFromString(stringRep)
root = convert(root)
if drawGraph {
fmt.Print("/* ")
}
tree.Print(root)
if drawGraph {
fmt.Print(" */")
}
fmt.Println()
if drawGraph {
tree.Draw(root)
}
}
func convert(node *tree.NumericNode) *tree.NumericNode {
if node == nil {
return nil
}
node.Left = convert(node.Left)
node.Right = convert(node.Right)
if node.Left != nil {
if node.Right == nil {
// left non-nil, right nil
return node.Left
}
// both left and right child non-nil
return node
}
if node.Right != nil {
if node.Left == nil {
// right non-nil, left nil
return node.Right
}
}
// both left and right nil
return node
}