Skip to content

Commit 0c73e52

Browse files
committed
add: go: 7-226
1 parent aa8f53e commit 0c73e52

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
// 226: Invert Binary Tree
2+
// https://leetcode.com/problems/invert-binary-tree/
3+
4+
package main
5+
6+
import "fmt"
7+
8+
type TreeNode struct {
9+
val any
10+
left *TreeNode
11+
right *TreeNode
12+
}
13+
14+
type Tree struct {
15+
root *TreeNode
16+
}
17+
18+
func creator(values []any, root **TreeNode, i, n int) *TreeNode {
19+
if n==0 {return nil}
20+
if i<n {
21+
temp := &TreeNode{values[i], nil, nil}
22+
*root = temp
23+
(*root).left = creator(values, &((*root).left), 2*i+1, n);
24+
(*root).right = creator(values, &((*root).right), 2*i+2, n);
25+
}
26+
return *root;
27+
}
28+
29+
func createTree(root **TreeNode, inputs []any) {
30+
creator(inputs, root, 0, len(inputs))
31+
}
32+
33+
func showTree(root *TreeNode) {
34+
var q []*TreeNode;
35+
var result [][]interface{}
36+
var c []interface{}
37+
if root==nil { fmt.Println("Empty !"); return; }
38+
q = append(q, root)
39+
q = append(q, nil)
40+
for len(q)!=0 {
41+
t := q[0]
42+
q = q[1:]
43+
if t==nil {
44+
result = append(result, c)
45+
c = make([]interface{}, 0)
46+
if len(q) > 0 {q = append(q, nil)}
47+
} else {
48+
c = append(c, t.val)
49+
if t.left!=nil {q = append(q, t.left)}
50+
if t.right!=nil {q = append(q, t.right)}
51+
}
52+
}
53+
54+
fmt.Print("["); for _, x := range result {
55+
fmt.Print("["); for _, y := range x {
56+
if y==nil { fmt.Print("NULL,"); continue; }
57+
fmt.Print(y,",")
58+
}; fmt.Print("\b],")
59+
}; fmt.Println("\b]")
60+
}
61+
62+
// SOLUTION
63+
func invertTree(root *TreeNode) *TreeNode {
64+
if root == nil {return root}
65+
left := invertTree(root.left)
66+
root.left = invertTree(root.right)
67+
root.right = left
68+
return root
69+
}
70+
71+
func main() {
72+
tree := Tree{}
73+
74+
// INPUT
75+
tn := []any{4,2,7,1,3,6,9}
76+
createTree(&tree.root, tn)
77+
78+
// OUTPUT
79+
result := invertTree(tree.root)
80+
showTree(result)
81+
}

0 commit comments

Comments
 (0)