NOTE
Binary Tree Preorder, Inorder, and Postorder Traversal
Notes on implementing preorder, inorder, and postorder traversal of a binary tree.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Problem Description
Print all nodes of a binary tree in preorder, inorder, and postorder respectively.
2. Approach
- Approach 1
- Recursion
- Approach 2
- Color marking
3. Implementation
package main
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
*
* @param root TreeNode the root of binary tree
* @return two-dimensional integer array
*/
func threeOrders(root *TreeNode) [][]int {
if root == nil {
return nil
}
res := make([][]int, 0)
pre := make([]int, 0)
preOrder(root, &pre)
res = append(res, pre)
mid := make([]int, 0)
midOrder(root, &mid)
res = append(res, mid)
post := make([]int, 0)
postOrder(root, &post)
res = append(res, post)
return res
}
func postOrder(root *TreeNode, res *[]int) {
if root == nil {
return
}
postOrder(root.Left, res)
postOrder(root.Right, res)
*res = append(*res, root.Val)
}
func midOrder(root *TreeNode, res *[]int) {
if root == nil {
return
}
midOrder(root.Left, res)
*res = append(*res, root.Val)
midOrder(root.Right, res)
}
func preOrder(root *TreeNode, res *[]int) {
if root == nil {
return
}
*res = append(*res, root.Val)
preOrder(root.Left, res)
preOrder(root.Right, res)
}
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub