Created
April 23, 2022 10:26
-
-
Save kanguki/01a625401c2f7bedbd3253b25eb2ac86 to your computer and use it in GitHub Desktop.
tree traversal in go (recursively)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type TreeNode struct { | |
Val int | |
Left *TreeNode | |
Right *TreeNode | |
} | |
func inorderTraversal(root *TreeNode) []int { | |
if root == nil { | |
return nil | |
} | |
output := []int{} | |
output = append(output, inorderTraversal(root.Left)...) | |
output = append(output, root.Val) | |
output = append(output, inorderTraversal(root.Right)...) | |
return output | |
} | |
func preorderTraversal(root *TreeNode) []int { | |
if root == nil { | |
return nil | |
} | |
output := []int{} | |
output = append(output, root.Val) | |
output = append(output, inorderTraversal(root.Left)...) | |
output = append(output, inorderTraversal(root.Right)...) | |
return output | |
} | |
func postorderTraversal(root *TreeNode) []int { | |
if root == nil { | |
return nil | |
} | |
output := []int{} | |
output = append(output, inorderTraversal(root.Left)...) | |
output = append(output, inorderTraversal(root.Right)...) | |
output = append(output, root.Val) | |
return output | |
} | |
func main() { | |
root := TreeNode{Val: 1} | |
root.Left = &TreeNode{Val: 2} | |
root.Left.Left = &TreeNode{Val: 4} | |
root.Right = &TreeNode{Val: 3} | |
root.Right.Left = &TreeNode{Val: 5} | |
root.Right.Right = &TreeNode{Val: 6} | |
fmt.Println(inorderTraversal(&root)) | |
fmt.Println(preorderTraversal(&root)) | |
fmt.Println(postorderTraversal(&root)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment