|
@@ -23,6 +23,9 @@ func main() {
|
|
|
inorder(&n1)
|
|
|
fmt.Println("\npostorder: ")
|
|
|
postorder(&n1)
|
|
|
+ fmt.Println("\nlevelorder: ")
|
|
|
+ levelorder(&n1)
|
|
|
+ fmt.Println()
|
|
|
}
|
|
|
|
|
|
func preorder(root *node) {
|
|
@@ -51,3 +54,22 @@ func postorder(root *node) {
|
|
|
postorder(root.right)
|
|
|
fmt.Printf("%d ", root.val)
|
|
|
}
|
|
|
+
|
|
|
+func levelorder(root *node) {
|
|
|
+ if root == nil {
|
|
|
+ return
|
|
|
+ }
|
|
|
+ queue := make([]*node, 0)
|
|
|
+ queue = append(queue, root)
|
|
|
+ for len(queue) != 0 {
|
|
|
+ head := queue[len(queue)-1]
|
|
|
+ queue = queue[:len(queue)-1]
|
|
|
+ fmt.Printf("%d ", head.val)
|
|
|
+ if head.left != nil {
|
|
|
+ queue = append(queue, head.left)
|
|
|
+ }
|
|
|
+ if head.right != nil {
|
|
|
+ queue = append(queue, head.right)
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|