Posted on by Kalkicode
Code Recursion

Find parent of every leaf nodes in binary tree in node js

Parent of leaf nodes in binary tree

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

/*
    Node JS program for
    Find parent of leaf nodes in binary tree
*/
// Binary Tree node
class TreeNode
{
	constructor(data)
	{
		// Set node value
		this.data = data;
		this.left = null;
		this.right = null;
	}
}
class BinaryTree
{
	constructor()
	{
		this.root = null;
	}
	//  Find the parent of leaf nodes using recursion
	leafParent(node, 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
					console.log(" NULL");
				}
				else
				{
					process.stdout.write("  " + parent.data);
				}
			}
			else
			{
				// Visit left subtree
				this.leafParent(node.left, node);
				// Visit right subtree
				this.leafParent(node.right, node);
			}
		}
	}
}

function main()
{
	// Create new binary trees
	var 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);
}
// Start program execution
main();

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.

New Comment