Find parent of every leaf nodes in binary tree in python

Python program for Find parent of every leaf nodes in binary tree. Here more solutions.
# Python 3 program for
# Find parent of leaf nodes in binary tree
# Binary Tree node
class TreeNode :
def __init__(self, data) :
# Set node value
self.data = data
self.left = None
self.right = None
class BinaryTree :
def __init__(self) :
# Set initial tree root to null
self.root = None
# Find the parent of leaf nodes using recursion
def leafParent(self, node, parent) :
if (node != None) :
# Check that node is leaf node or not
if ((node.left == None and node.right == None)) :
if (parent == None) :
# When one node of tree
print(" NULL")
else :
print(parent.data, end =" ")
else :
# Visit left subtree
self.leafParent(node.left, node)
# Visit right subtree
self.leafParent(node.right, node)
def main() :
# Create new binary trees
tree = BinaryTree()
# 34
# / \
# / \
# -4 10
# / \ \
# 7 12 6
# / / \
# 4 6 8
# / \
# 9 1
# -----------------
# Constructing binary tree
tree.root = TreeNode(34)
tree.root.left = TreeNode(-4)
tree.root.left.right = TreeNode(12)
tree.root.left.right.left = TreeNode(6)
tree.root.left.right.left.left = TreeNode(9)
tree.root.left.right.left.right = TreeNode(1)
tree.root.left.right.right = TreeNode(8)
tree.root.left.left = TreeNode(7)
tree.root.left.left.left = TreeNode(4)
tree.root.right = TreeNode(10)
tree.root.right.right = TreeNode(6)
# Test
tree.leafParent(tree.root, None)
if __name__=="__main__":
main()
Output
7 6 6 12 10
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