Bottom right view of binary tree in scala
Scala program for Bottom right view of binary tree. Here problem description and other solutions.
import scala.collection.mutable._;
/*
Scala program for
Print bottom-right view of a binary tree
*/
// Binary Tree Node
class TreeNode(var data: Int,
var left: TreeNode,
var right: TreeNode)
{
def this(data: Int)
{
// Set node value
this(data, null, null);
}
}
class BinaryTree(var root: TreeNode)
{
def this()
{
this(null);
}
// Find bottom right elements
def bottomRightView(node: TreeNode,
distance: Int,
record: HashMap[Int, Int]): Unit = {
if (node != null)
{
// Add node of specific distance.
// This is adding a new element or
// update existing value
record.addOne(distance, node.data);
// Visit left subtree And
// Here increase the distance by 1
bottomRightView(node.left, distance + 1, record);
// Visit to right subtree
bottomRightView(node.right, distance, record);
}
}
def printBottomRight(): Unit = {
// This is store result
var record: HashMap[Int, Int] = new HashMap[Int, Int]();
bottomRightView(this.root, 0, record);
var distance: Int = 0;
while (distance < record.size)
{
// Display bottom right element
print(" " + record.get(distance).get);
distance += 1;
}
}
}
object Main
{
def main(args: Array[String]): Unit = {
// Create new tree
var tree: BinaryTree = new BinaryTree();
/*
Binary Tree
-----------------------
10
/ \
2 4
/ / \
3 6 5
\
7
/ \
8 11
[⤣⤣⤣⤣]
View position
*/
// Add node
tree.root = new TreeNode(10);
tree.root.left = new TreeNode(2);
tree.root.left.left = new TreeNode(3);
tree.root.right = new TreeNode(4);
tree.root.right.right = new TreeNode(5);
tree.root.right.left = new TreeNode(6);
tree.root.right.left.right = new TreeNode(7);
tree.root.right.left.right.left = new TreeNode(8);
tree.root.right.left.right.right = new TreeNode(11);
// Test
tree.printBottomRight();
}
}
Output
5 11 8
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