Bottom right view of binary tree in vb.net
Vb program for Bottom right view of binary tree. Here problem description and other solutions.
' Include namespace system
Imports System
Imports System.Collections.Generic
Imports System.Collections
' Vb.net program for
' Print bottom-right view of a binary tree
' Binary Tree Node
Public Class TreeNode
Public data As Integer
Public left As TreeNode
Public right As TreeNode
Public Sub New(ByVal data As Integer)
' Set node value
Me.data = data
Me.left = Nothing
Me.right = Nothing
End Sub
End Class
public Class BinaryTree
Public root As TreeNode
Public Sub New()
' Set initial tree root
Me.root = Nothing
End Sub
' Find bottom right elements
Public Sub bottomRightView(ByVal node As TreeNode,
ByVal distance As Integer,
ByVal record As Dictionary(Of Integer, Integer))
if (node IsNot Nothing) Then
' 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
Me.bottomRightView(node.left, distance + 1, record)
' Visit to right subtree
Me.bottomRightView(node.right, distance, record)
End If
End Sub
Public Sub printBottomRight()
' This is store result
Dim record As Dictionary(Of Integer, Integer) =
New Dictionary(Of Integer, Integer)()
Me.bottomRightView(Me.root, 0, record)
Dim distance As Integer = 0
while (distance < record.Count)
' Display bottom right element
Console.Write(" {0}", record(distance))
distance += 1
End While
End Sub
Public Shared Sub Main(ByVal args As String())
' Create new tree
Dim tree As 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()
End Sub
End Class
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