|
@@ -1,7 +1,7 @@
|
|
|
package main
|
|
|
|
|
|
import (
|
|
|
- "fmt"
|
|
|
+ "strconv"
|
|
|
)
|
|
|
|
|
|
// ListNode ...
|
|
@@ -38,25 +38,54 @@ func minInt(x, y int) int {
|
|
|
return y
|
|
|
}
|
|
|
|
|
|
-func list2str(head *ListNode) string {
|
|
|
+func toLinkedList(num []int) *ListNode {
|
|
|
+ length := len(num)
|
|
|
+ if length == 0 {
|
|
|
+ return nil
|
|
|
+ }
|
|
|
+ head := ListNode{num[0], nil}
|
|
|
+ curr := &head
|
|
|
+ for i := 1; i < length; i++ {
|
|
|
+ curr.Next = &ListNode{num[i], nil}
|
|
|
+ curr = curr.Next
|
|
|
+ }
|
|
|
+ return &head
|
|
|
+}
|
|
|
+
|
|
|
+func printList(head *ListNode) {
|
|
|
curr := head
|
|
|
- str := make([]rune, 0)
|
|
|
for curr != nil {
|
|
|
- str = append(str, rune(curr.Val+'0'))
|
|
|
+ print(strconv.FormatInt(int64(curr.Val), 10), " ")
|
|
|
curr = curr.Next
|
|
|
}
|
|
|
- return string(str)
|
|
|
+ println()
|
|
|
}
|
|
|
|
|
|
-func printTree(root *TreeNode) {
|
|
|
+func printTree(root *TreeNode) { // Level order traversal
|
|
|
if root == nil {
|
|
|
+ println("nil")
|
|
|
return
|
|
|
}
|
|
|
- if root.Left != nil {
|
|
|
- printTree(root.Left)
|
|
|
- }
|
|
|
- if root.Right != nil {
|
|
|
- printTree(root.Right)
|
|
|
+ queue := make([]*TreeNode, 0) // Important!
|
|
|
+ queue = append(queue, root)
|
|
|
+ for len(queue) != 0 {
|
|
|
+ curr := queue[0]
|
|
|
+ queue = queue[1:] // Dequeue
|
|
|
+ if curr == nil {
|
|
|
+ print("nil ")
|
|
|
+ continue
|
|
|
+ }
|
|
|
+ print(curr.Val, " ")
|
|
|
+ if curr.Left != nil {
|
|
|
+ queue = append(queue, curr.Left)
|
|
|
+ } else if curr.Right != nil {
|
|
|
+ queue = append(queue, nil)
|
|
|
+ }
|
|
|
+ if curr.Right != nil {
|
|
|
+ queue = append(queue, curr.Right)
|
|
|
+ } else if curr.Left != nil {
|
|
|
+ queue = append(queue, nil)
|
|
|
+ }
|
|
|
}
|
|
|
- fmt.Print(root.Val, " ")
|
|
|
+ println()
|
|
|
}
|