# Find parent of every leaf nodes in binary tree in java

Java program for Find parent of every leaf nodes in binary tree. Here mentioned other language solution.

``````/*
Java program for
Find parent of leaf nodes in binary tree
*/
// Binary Tree node
class TreeNode
{
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode(int data)
{
// Set node value
this.data = data;
this.left = null;
this.right = null;
}
}
public class BinaryTree
{
public TreeNode root;
public BinaryTree()
{
// Set initial tree root to null
this.root = null;
}
//  Find the parent of leaf nodes using recursion
public void leafParent(TreeNode node, TreeNode parent)
{
if (node != null)
{
// Check that node is leaf node or not
if ((node.left == null && node.right == null))
{
if (parent == null)
{
// When one node of tree
System.out.println(" NULL");
}
else
{
System.out.print("  " + parent.data);
}
}
else
{
// Visit left subtree
leafParent(node.left, node);
// Visit right subtree
leafParent(node.right, node);
}
}
}
public static void main(String[] args)
{
// Create new binary trees
BinaryTree tree = new BinaryTree();
/*
34
/ \
/   \
-4     10
/ \     \
7   12    6
/   / \
4   6   8
/ \
9   1
-----------------
Constructing binary tree
*/
tree.root = new TreeNode(34);
tree.root.left = new TreeNode(-4);
tree.root.left.right = new TreeNode(12);
tree.root.left.right.left = new TreeNode(6);
tree.root.left.right.left.left = new TreeNode(9);
tree.root.left.right.left.right = new TreeNode(1);
tree.root.left.right.right = new TreeNode(8);
tree.root.left.left = new TreeNode(7);
tree.root.left.left.left = new TreeNode(4);
tree.root.right = new TreeNode(10);
tree.root.right.right = new TreeNode(6);
// Test
tree.leafParent(tree.root, null);
}
}``````

Output

``  7  6  6  12  10``

## Comment

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.