-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path00226-invert_binary_tree.go
81 lines (69 loc) · 1.81 KB
/
00226-invert_binary_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
// 226: Invert Binary Tree
// https://leetcode.com/problems/invert-binary-tree/
package main
import "fmt"
type TreeNode struct {
val any
left *TreeNode
right *TreeNode
}
type Tree struct {
root *TreeNode
}
func creator(values []any, root **TreeNode, i, n int) *TreeNode {
if n==0 {return nil}
if i<n {
temp := &TreeNode{values[i], nil, nil}
*root = temp
(*root).left = creator(values, &((*root).left), 2*i+1, n);
(*root).right = creator(values, &((*root).right), 2*i+2, n);
}
return *root;
}
func createTree(root **TreeNode, inputs []any) {
creator(inputs, root, 0, len(inputs))
}
func showTree(root *TreeNode) {
var q []*TreeNode;
var result [][]interface{}
var c []interface{}
if root==nil { fmt.Println("Empty !"); return; }
q = append(q, root)
q = append(q, nil)
for len(q)!=0 {
t := q[0]
q = q[1:]
if t==nil {
result = append(result, c)
c = make([]interface{}, 0)
if len(q) > 0 {q = append(q, nil)}
} else {
c = append(c, t.val)
if t.left!=nil {q = append(q, t.left)}
if t.right!=nil {q = append(q, t.right)}
}
}
fmt.Print("["); for _, x := range result {
fmt.Print("["); for _, y := range x {
if y==nil { fmt.Print("NULL,"); continue; }
fmt.Print(y,",")
}; fmt.Print("\b],")
}; fmt.Println("\b]")
}
// SOLUTION
func invertTree(root *TreeNode) *TreeNode {
if root == nil {return root}
left := invertTree(root.left)
root.left = invertTree(root.right)
root.right = left
return root
}
func main() {
tree := Tree{}
// INPUT
tn := []any{4,2,7,1,3,6,9}
createTree(&tree.root, tn)
// OUTPUT
result := invertTree(tree.root)
showTree(result)
}