Bottom right view of binary tree in swift
Swift program for Bottom right view of binary tree. Here problem description and other solutions.
import Foundation
/*
Swift 4 program for
Print bottom-right view of a binary tree
*/
// Binary Tree Node
class TreeNode
{
var data: Int;
var left: TreeNode? ;
var right: TreeNode? ;
init(_ data: Int)
{
// Set node value
self.data = data;
self.left = nil;
self.right = nil;
}
}
class BinaryTree
{
var root: TreeNode? ;
init()
{
self.root = nil;
}
// Find bottom right elements
func bottomRightView(_ node: TreeNode? ,
_ distance : Int,
_ record: inout[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
self.bottomRightView(node!.left, distance + 1, &record);
// Visit to right subtree
self.bottomRightView(node!.right, distance, &record);
}
}
func printBottomRight()
{
// This is store result
var record: [Int: Int] = [Int: Int]();
self.bottomRightView(self.root, 0, &record);
var distance: Int = 0;
while (distance < record.count)
{
// Display bottom right element
print("",record[distance]!, terminator: " ");
distance += 1;
}
}
static func main()
{
// Create new tree
let tree: BinaryTree = BinaryTree();
/*
Binary Tree
-----------------------
10
/ \
2 4
/ / \
3 6 5
\
7
/ \
8 11
[⤣⤣⤣⤣]
View position
*/
// Add node
tree.root = TreeNode(10);
tree.root!.left = TreeNode(2);
tree.root!.left!.left = TreeNode(3);
tree.root!.right = TreeNode(4);
tree.root!.right!.right = TreeNode(5);
tree.root!.right!.left = TreeNode(6);
tree.root!.right!.left!.right = TreeNode(7);
tree.root!.right!.left!.right!.left = TreeNode(8);
tree.root!.right!.left!.right!.right = TreeNode(11);
// Test
tree.printBottomRight();
}
}
BinaryTree.main();
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