Skip to main content

Bottom right view of binary tree in golang

Go program for Bottom right view of binary tree. Here problem description and other solutions.

package main
import "fmt"
/* 
  Go program for
  Print bottom-right view of a binary tree
*/
// 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,
	}
}
// Find bottom right elements
func(this BinaryTree) bottomRightView(node * TreeNode, 
	distance int, record map[int] int) {
	if node != nil {
		// Add node of specific distance.
		// This is adding a new element or
		// update existing value
		record[distance] = node.data
		// Visit left subtree And
		// Here increase the distance by 1
		this.bottomRightView(node.left, distance + 1, record)
		// Visit to right subtree
		this.bottomRightView(node.right, distance, record)
	}
}
func(this BinaryTree) printBottomRight() {
	// This is store result
	var record = make(map[int] int)
	this.bottomRightView(this.root, 0, record)
	var distance int = 0
	for (distance < len(record)) {
		// Display bottom right element
		fmt.Print("  ", record[distance])
		distance += 1
	}
}
func main() {
	// Create new tree
	var tree * BinaryTree = getBinaryTree()
	/*
	  Binary Tree
	  -----------------------
	      10
	     /  \
	    2    4
	   /    / \
	  3    6   5
	        \
	         7
	       /  \
	      8    11

	       
	            [⤣⤣⤣⤣]
	            View position
	*/
	// Add node
	tree.root = getTreeNode(10)
	tree.root.left = getTreeNode(2)
	tree.root.left.left = getTreeNode(3)
	tree.root.right = getTreeNode(4)
	tree.root.right.right = getTreeNode(5)
	tree.root.right.left = getTreeNode(6)
	tree.root.right.left.right = getTreeNode(7)
	tree.root.right.left.right.left = getTreeNode(8)
	tree.root.right.left.right.right = getTreeNode(11)
	// Test
	tree.printBottomRight()
}

Output

  5  11  8




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