Skip to main content

Inorder traversal of binary tree with recursion in golang

Go program for Inorder traversal of binary tree with recursion. Here problem description and explanation.

package main
import "fmt"
/* 
  Go Program for
  inorder tree traversal of a Binary Tree
  using recursion
*/
// Binary Tree Node
type TreeNode struct {
    data int
    left * TreeNode
    right * TreeNode
}
func getTreeNode(data int) * TreeNode {
    return &TreeNode {data,nil,nil}
}
type BinaryTree struct {
    root * TreeNode
}
func getBinaryTree() * BinaryTree {

    return &BinaryTree {nil}
}
// Display Inorder view of binary tree
func(this BinaryTree) inorder(node * TreeNode) {
    if node != nil {
        // Visit left subtree
        this.inorder(node.left)
        //Print node value
        fmt.Print("  ", node.data)
        // Visit right subtree
        this.inorder(node.right)
    }
}
func main() {
    // Create new tree
    var tree * BinaryTree = getBinaryTree()
    /*
        Make A Binary Tree
        ----------------
            15
           /  \
          24   54
         /    /  \
        35   62   13
    */
    // Add tree TreeNode
    tree.root = getTreeNode(15)
    tree.root.left = getTreeNode(24)
    tree.root.right = getTreeNode(54)
    tree.root.right.right = getTreeNode(13)
    tree.root.right.left = getTreeNode(62)
    tree.root.left.left = getTreeNode(35)
    // Display Tree Node
    tree.inorder(tree.root)
}

Output

  35  24  15  62  54  13




Comment

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