Check for foldable binary tree in vb.net
Vb program for Check for foldable binary tree. Here problem description and other solutions.
' Include namespace system
Imports System
' Vb.net program for
' Check if binary tree is foldable binary tree
' Using recursion
' 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
Public Function isFoldable(ByVal leftRoot As TreeNode,
ByVal rightRoot As TreeNode) As Boolean
if (leftRoot Is Nothing AndAlso
rightRoot Is Nothing) Then
' When both node empty
Return True
ElseIf (leftRoot IsNot Nothing AndAlso
rightRoot IsNot Nothing AndAlso
Me.isFoldable(leftRoot.left, rightRoot.right) AndAlso
Me.isFoldable(leftRoot.right, rightRoot.left)) Then
' When
' Valid the properties of foldable tree
Return True
End If
' Fail case
Return False
End Function
' Display tree element inorder form
Public Sub inorder(ByVal node As TreeNode)
if (node IsNot Nothing) Then
' Visit to left subtree
Me.inorder(node.left)
' Print node value
Console.Write(" " + node.data.ToString())
' Visit to right subtree
Me.inorder(node.right)
End If
End Sub
Public Shared Sub Main(ByVal args As String())
' Create new tree
Dim tree As BinaryTree = New BinaryTree()
' Binary Tree
' -----------------------
' 5
' / \
' 7 4
' / \
' 1 2
' \ /
' 2 5
' Binary tree nodes
tree.root = New TreeNode(5)
tree.root.left = New TreeNode(7)
tree.root.right = New TreeNode(4)
tree.root.left.left = New TreeNode(1)
tree.root.right.right = New TreeNode(2)
tree.root.right.right.left = New TreeNode(5)
tree.root.left.left.right = New TreeNode(2)
' Display Tree elements
tree.inorder(tree.root)
Dim result As Boolean = tree.isFoldable(tree.root.left,
tree.root.right)
if (result = True) Then
Console.WriteLine( vbLf &" Foldable Tree")
Else
Console.WriteLine( vbLf &" Not Foldable Tree")
End IF
' 5
' / \
' 7 4
' / \
' 1 2
' \ /
' 2 5
' \
' 3
' Case 2
tree.root.left.left.right.right = New TreeNode(3)
tree.inorder(tree.root)
result = tree.isFoldable(tree.root.left, tree.root.right)
if (result = True) Then
Console.WriteLine( vbLf &" Foldable Tree")
Else
Console.WriteLine( vbLf &" Not Foldable Tree")
End IF
End Sub
End Class
Output
1 2 7 5 4 5 2
Foldable Tree
1 2 3 7 5 4 5 2
Not Foldable Tree
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