Morris preorder traversal in golang
Go program for Morris preorder traversal. Here problem description and explanation.
package main
import "fmt"
/*
Go program for
Morris traversal preorder
*/
// Binary Tree Node
type TreeNode struct {
data int
left * TreeNode
right * TreeNode
}
func getTreeNode(data int) * TreeNode {
// return new TreeNode
return &TreeNode {data,nil,nil}
}
type BinaryTree struct {
root * TreeNode
}
func getBinaryTree() * BinaryTree {
// return new BinaryTree
return &BinaryTree {nil}
}
// Recursive function
// Display preorder view of binary tree
func(this BinaryTree) preorder(node * TreeNode) {
if node != nil {
// Print node value
fmt.Print(" ", node.data)
this.preorder(node.left)
this.preorder(node.right)
}
}
// iterative preorder tree traversal
func(this BinaryTree) morrisPreorder() {
if this.root == nil {
return
}
var current * TreeNode = this.root
var auxiliary * TreeNode = nil
// iterating tree nodes
for (current != nil) {
if current.left == nil {
// Print node value
fmt.Print(" ", current.data)
// Visit to right childs
current = current.right
} else {
auxiliary = current.left
// Find rightmost node which is not
// equal to current node
for (auxiliary.right != nil &&
auxiliary.right != current) {
// Visit to right subtree
auxiliary = auxiliary.right
}
if auxiliary.right != current {
// Print node value
fmt.Print(" ", current.data)
// Connect rightmost right node to current node
auxiliary.right = current
// Visit to left childs
current = current.left
} else {
// unlink
auxiliary.right = nil
// Visit to right child
current = current.right
}
}
}
fmt.Print("\n")
}
func main() {
// Create new tree
var tree * BinaryTree = getBinaryTree()
/*
Create Binary Tree
4
/ \
8 10
/ \ / \
1 6 7 -3
/
9
*/
// Add tree node
tree.root = getTreeNode(4)
tree.root.left = getTreeNode(8)
tree.root.left.left = getTreeNode(1)
tree.root.right = getTreeNode(10)
tree.root.right.right = getTreeNode(-3)
tree.root.right.left = getTreeNode(7)
tree.root.left.right = getTreeNode(6)
tree.root.left.right.left = getTreeNode(9)
fmt.Println("\n Recursive Preorder")
// Display preorder elements
tree.preorder(tree.root)
fmt.Println("\n Morris Preorder")
tree.morrisPreorder()
}
Output
Recursive Preorder
4 8 1 6 9 10 7 -3
Morris Preorder
4 8 1 6 9 10 7 -3
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment