The most intuitive way in my mind is level-order way: Print all node on root level from left to right, and then its child level, and so on. Level order of example graph is 0 1 2 3 4 5 6 7 8.
But how about depth-first way? There are 3 actions when we move on a tree node:
V: Visiting, any operation on current node, i.e. print, assign…
L: Move to left child.
R: Move to right child.
For the order of these three actions with a constraint that L has to be front of R, we can get three permuations: VLR, LVR, LRV. Which is called pre-order, in-order, post-order, depend on where V is positioned.
Let us see code examples below:
Binary Tree Data Structure
First, we need to define a tree node object. A TreeNode contains a int value and two pointers reference to its two children.
1 2 3 4 5 6
// Go type TreeNode struct { Val int Left *TreeNode Right *TreeNode }
// Go // Iterative funcprintTreeNodeLevelOrder(Root *TreeNode) { if Root == nil { return } Level := []*TreeNode{Root}
forlen(Level) > 0 { // while level is not empty NextLevel := []*TreeNode{} for _, Node := range Level { // Iterate through current level fmt.Printf("%v ", Node.Val) // Visiting // Push children into next level queue if existing if Node.Left != nil { NextLevel = append(NextLevel, Node.Left) } if Node.Right != nil { NextLevel = append(NextLevel, Node.Right) } } Level = NextLevel // Move on to next level } }
Preorder Traversal
1 2 3 4 5 6 7 8 9 10
// Go // Recursive funcprintTreeNodePreorder(Node *TreeNode) { if Node == nil { return } fmt.Printf("%v ", Node.Val) // V printTreeNodePreorder(Node.Left) // L printTreeNodePreorder(Node.Right) // R }
Inorder Traversal
1 2 3 4 5 6 7 8 9 10
// Go // Recursive funcprintTreeNodeInorder(Node *TreeNode) { if Node == nil { return } printTreeNodeInorder(Node.Left) // L fmt.Printf("%v ", Node.Val) // V printTreeNodeInorder(Node.Right) // R }
Postorder Traversal
1 2 3 4 5 6 7 8 9 10
// Go // Recursive funcprintTreeNodePostorder(Node *TreeNode) { if Node == nil { return } printTreeNodePostorder(Node.Left) // L printTreeNodePostorder(Node.Right) // R fmt.Printf("%v ", Node.Val) // V }
Result
Create a tree instance as example graph and call functions we have just implemented above.