Skip to main content

Print all paths from root node to leaf

The problem is to print all paths from the root node to each leaf node in a binary tree. A path is a sequence of nodes starting from the root and ending at a leaf node, where each node is connected to its child nodes through edges.

Example

Consider the binary tree:


     1
    / \
   2   3
  /   / \
 4   5   6
  \      / \
   7    8   11
        / \
       9   10

The paths from the root to each leaf node are:

  1. [1, 2, 4, 7]
  2. [1, 3, 5]
  3. [1, 3, 6, 8, 9]
  4. [1, 3, 6, 8, 10]
  5. [1, 3, 6, 11]

Idea to Solve the Problem

To print all paths from the root node to each leaf node, we can use a recursive approach. We will perform a depth-first search (DFS) on the binary tree, and during the traversal, we will maintain a stack to store the nodes in the current path. When we reach a leaf node, we will print the elements in the stack, which represent the path from the root to that leaf node.

Algorithm

  1. Create a custom stack structure to hold binary tree nodes and their next pointers.
  2. Define a function insert(data) to create new binary tree nodes and return their reference.
  3. Define a function push(tree_node, head) to add a new element into the stack and return the updated stack top.
  4. Define a function pop(&top) to remove the top element from the stack.
  5. Define a function print_path(temp) to recursively print the path from the root to the leaf node.
  6. Define a function show_path(root, &head) to collect path information using the stack and print the paths to leaf nodes.
    • If root is not NULL:
      • Push root into the stack.
      • Recursively call show_path(root->left, &head).
      • Recursively call show_path(root->right, &head).
      • If root is a leaf node (both left and right children are NULL), print the elements in the stack as the path.
      • Pop the top element from the stack.
  7. In the main function, construct the binary tree and call the show_path function to print all paths.

Code Solution

/*
  C Program 
  Print all paths from root node to leaf
*/
#include <stdio.h>
#include <stdlib.h>

//Structure of Binary Node
struct Node
{
	int data;
	struct Node *left, *right;
};
//Define the custom stack structure
struct MyStack
{
	//First is element of Binary tree node
	struct Node *element;
	//Second are used to hold information of next node
	struct MyStack *next;
};
//Create a binary tree nodes and node fields (data,pointer) 
//And returning the reference of newly nodes
struct Node *insert(int data)
{
	//create dynamic memory to new binary tree node
	struct Node *new_node = (struct Node *) malloc(sizeof(struct Node));
	if (new_node != NULL)
	{
		//set data and pointer values
		new_node->data = data;
		new_node->left = NULL; //Initially node left-child is NULL
		new_node->right = NULL; //Initially node right-child is NULL
	}
	else
	{
		printf("Memory Overflow\n");
		exit(0); //Terminate program execution
	}
	//return reference
	return new_node;
}
//Create a new stack element and return this newly node
struct MyStack *push(struct Node *tree_node, struct MyStack *head)
{
	//Create new node of Stack
	struct MyStack *node = (struct MyStack *) malloc(sizeof(struct MyStack));
	if (node != NULL)
	{
		//Set tree node
		node->element = tree_node;
		//Connect new node into head of Stack
		node->next = head;
	}
	else
	{
		printf("Memory Overflow\n");
		//Terminate program execution
		exit(0);
	}
	return node;
}
//Remove a top element of stack
void pop(struct MyStack **top)
{
	if ( *top != NULL)
	{
		struct MyStack *remove = *top;
		//Visit to next top element
		*top = remove->next;
		//set remove node values
		remove->element = NULL;
		remove->next = NULL;
		//free node memory
		free(remove);
		remove = NULL;
	}
}
//Function which is display the path from root to leaf 
void print_path(struct MyStack *temp)
{
	if (temp != NULL)
	{
		print_path(temp->next);
		printf("%3d", temp->element->data);
	}
}
//This function are collect path information using stack and when get leaf node then displaying node value
void show_path(struct Node *root, struct MyStack **head)
{
	if (root != NULL)
	{
		//Add a new element into Stack
		*head = push(root, *head);
		show_path(root->left, head);
		show_path(root->right, head);
		if (root->left == NULL && root->right == NULL)
		{
			//when get leaf node then display path
			printf("\n[");
			print_path( *head);
			printf(" ]\n");
		}
		pop(head);
	}
}
int main()
{
	struct Node *root = NULL;
	/*Make A Binary Tree
	-----------------------
	        1
	       /  \
	      2    3
	     /    /  \
	    4    5    6
	     \       / \
	      7     8   11
	           / \
	          9   10
	*/
	//Insert node into Binary tree
	root = insert(1);
	root->left = insert(2);
	root->right = insert(3);
	root->right->right = insert(6);
	root->right->left = insert(5);
	root->left->left = insert(4);
	root->left->left->right = insert(7);
	root->right->right->left = insert(8);
	root->right->right->left->left = insert(9);
	root->right->right->left->right = insert(10);
	root->right->right->right = insert(11);
	struct MyStack *head = NULL;
	//Display root to all leaf path
	show_path(root, & head);
	return 0;
}

Output

[  1  2  4  7 ]

[  1  3  5 ]

[  1  3  6  8  9 ]

[  1  3  6  8 10 ]

[  1  3  6 11 ]
/*
  Java Program
  Print all paths from root node to leaf
*/
//Tree node
class Node
{
	public int data;
	public Node left;
	public Node right;
	//Set initial value of Binary Tree Node
	public Node(int data)
	{
		this.data = data;
		this.left = null;
		this.right = null;
	}
}
//Define the custom stack class
class MyStack
{
	public Node element;
	public MyStack next;
	public MyStack(Node element)
	{
		this.element = element;
		this.next = null;
	}
}
class BinaryTree
{
	public MyStack top;
	public Node root;
	public BinaryTree()
	{
		this.top = null;
		this.root = null;
	}
	//add element into top of stack
	public void push(Node element)
	{
		MyStack new_node = new MyStack(element);
		if (new_node != null)
		{
			new_node.next = this.top;
			this.top = new_node;
		}
	}
	//Remove top element
	public void pop()
	{
		if (this.top == null)
		{
			//already empty
			return;
		}
		MyStack temp = this.top;
		this.top = temp.next;
		temp = null;
	}
	//Function which is display the path from root to leaf 
	public void print_path(MyStack temp)
	{
		if (temp != null)
		{
			print_path(temp.next);
			System.out.print(" " + temp.element.data + " ");
		}
	}
	//This function are collect path information using stack and when get leaf node then displaying node value
	public void show_path(Node root)
	{
		if (root != null)
		{
			//Add a new element into Stack
			this.push(root);
			this.show_path(root.left);
			this.show_path(root.right);
			if (root.left == null && root.right == null)
			{
				System.out.print("\n[");
				this.print_path(this.top);
				System.out.print(" ]\n");
			}
			this.pop();
		}
	}
	public static void main(String[] args)
	{
		BinaryTree obj = new BinaryTree();
		/* Make A Binary Tree
		-----------------------
		        1
		       /  \
		      2    3
		     /    /  \
		    4    5    6
		     \       / \
		      7     8   11
		           / \
		          9   10
		*/
		//Insert node into Binary tree
		obj.root = new Node(1);
		obj.root.left = new Node(2);
		obj.root.right = new Node(3);
		obj.root.right.right = new Node(6);
		obj.root.right.left = new Node(5);
		obj.root.left.left = new Node(4);
		obj.root.left.left.right = new Node(7);
		obj.root.right.right.left = new Node(8);
		obj.root.right.right.left.left = new Node(9);
		obj.root.right.right.left.right = new Node(10);
		obj.root.right.right.right = new Node(11);
		//Display root to all leaf path
		obj.show_path(obj.root);
	}
}

Output

[ 1  2  4  7  ]

[ 1  3  5  ]

[ 1  3  6  8  9  ]

[ 1  3  6  8  10  ]

[ 1  3  6  11  ]
/*
  C++ Program
  Print all paths from root node to leaf
*/
//Tree node
#include<iostream>

using namespace std;
class Node
{
	public: int data;
	Node * left;
	Node * right;
	//Set initial value of Binary Tree Node
	Node(int data)
	{
		this->data = data;
		this->left = NULL;
		this->right = NULL;
	}
};
//Define the custom stack class
class MyStack
{
	public: Node * element;
	MyStack * next;
	MyStack(Node * element)
	{
		this->element = element;
		this->next = NULL;
	}
};
class BinaryTree
{
	public: MyStack * top;
	Node * root;
	BinaryTree()
	{
		this->top = NULL;
		this->root = NULL;
	}
	//add element into top of stack
	void push(Node * element)
	{
		MyStack * new_node = new MyStack(element);
		if (new_node != NULL)
		{
			new_node->next = this->top;
			this->top = new_node;
		}
	}
	//Remove top element
	void pop()
	{
		if (this->top == NULL)
		{
			//already empty
			return;
		}
		MyStack * temp = this->top;
		this->top = temp->next;
		temp = NULL;
	}
	//Function which is display the path from root to leaf 
	void print_path(MyStack * temp)
	{
		if (temp != NULL)
		{
			print_path(temp->next);
			cout << " " << temp->element->data << " ";
		}
	}
	//This function are collect path information using stack and when get leaf node then displaying node value
	void show_path(Node * root)
	{
		if (root != NULL)
		{
			//Add a new element into Stack
			this->push(root);
			this->show_path(root->left);
			this->show_path(root->right);
			if (root->left == NULL && root->right == NULL)
			{
				cout << "\n[";
				this->print_path(this->top);
				cout << " ]\n";
			}
			this->pop();
		}
	}
};
int main()
{
	BinaryTree obj =  BinaryTree();
	/* Make A Binary Tree
			-----------------------
			        1
			       /  \
			      2    3
			     /    /  \
			    4    5    6
			     \       / \
			      7     8   11
			           / \
			          9   10
			*/
	//Insert node into Binary tree
	obj.root = new Node(1);
	obj.root->left = new Node(2);
	obj.root->right = new Node(3);
	obj.root->right->right = new Node(6);
	obj.root->right->left = new Node(5);
	obj.root->left->left = new Node(4);
	obj.root->left->left->right = new Node(7);
	obj.root->right->right->left = new Node(8);
	obj.root->right->right->left->left = new Node(9);
	obj.root->right->right->left->right = new Node(10);
	obj.root->right->right->right = new Node(11);
	//Display root to all leaf path
	obj.show_path(obj.root);
	return 0;
}

Output

[ 1  2  4  7  ]

[ 1  3  5  ]

[ 1  3  6  8  9  ]

[ 1  3  6  8  10  ]

[ 1  3  6  11  ]
/*
  C# Program
  Print all paths from root node to leaf
*/
//Tree node
using System;
class Node
{
	public int data;
	public Node left;
	public Node right;
	//Set initial value of Binary Tree Node
	public Node(int data)
	{
		this.data = data;
		this.left = null;
		this.right = null;
	}
}
//Define the custom stack class
class MyStack
{
	public Node element;
	public MyStack next;
	public MyStack(Node element)
	{
		this.element = element;
		this.next = null;
	}
}
class BinaryTree
{
	public MyStack top;
	public Node root;
	public BinaryTree()
	{
		this.top = null;
		this.root = null;
	}
	//add element into top of stack
	public void push(Node element)
	{
		MyStack new_node = new MyStack(element);
		if (new_node != null)
		{
			new_node.next = this.top;
			this.top = new_node;
		}
	}
	//Remove top element
	public void pop()
	{
		if (this.top == null)
		{
			return;
		}
		MyStack temp = this.top;
		this.top = temp.next;
		temp = null;
	}
	//Function which is display the path from root to leaf 
	public void print_path(MyStack temp)
	{
		if (temp != null)
		{
			print_path(temp.next);
			Console.Write(" " + temp.element.data + " ");
		}
	}
	//This function are collect path information using stack and when get leaf node then displaying node value
	public void show_path(Node root)
	{
		if (root != null)
		{
			//Add a new element into Stack
			this.push(root);
			this.show_path(root.left);
			this.show_path(root.right);
			if (root.left == null && root.right == null)
			{
				Console.Write("\n[");
				this.print_path(this.top);
				Console.Write(" ]\n");
			}
			this.pop();
		}
	}
	public static void Main(String[] args)
	{
		BinaryTree obj = new BinaryTree();
		/* Make A Binary Tree
				-----------------------
				        1
				       /  \
				      2    3
				     /    /  \
				    4    5    6
				     \       / \
				      7     8   11
				           / \
				          9   10
				*/
		//Insert node into Binary tree
		//Insert node into Binary tree
		obj.root = new Node(1);
		obj.root.left = new Node(2);
		obj.root.right = new Node(3);
		obj.root.right.right = new Node(6);
		obj.root.right.left = new Node(5);
		obj.root.left.left = new Node(4);
		obj.root.left.left.right = new Node(7);
		obj.root.right.right.left = new Node(8);
		obj.root.right.right.left.left = new Node(9);
		obj.root.right.right.left.right = new Node(10);
		obj.root.right.right.right = new Node(11);
		//Display root to all leaf path
		obj.show_path(obj.root);
	}
}

Output

[ 1  2  4  7  ]

[ 1  3  5  ]

[ 1  3  6  8  9  ]

[ 1  3  6  8  10  ]

[ 1  3  6  11  ]
<?php
/*
  Php Program
  Print all paths from root node to leaf
*/
//Tree node
class Node
{
	public $data;
	public $left;
	public $right;
	//Set initial value of Binary Tree Node
	function __construct($data)
	{
		$this->data = $data;
		$this->left = null;
		$this->right = null;
	}
}
//Define the custom stack class
class MyStack
{
	public $element;
	public $next;

	function __construct($element)
	{
		$this->element = $element;
		$this->next = null;
	}
}
class BinaryTree
{
	public $top;
	public $root;

	function __construct()
	{
		$this->top = null;
		$this->root = null;
	}
	//add element into top of stack
	function push($element)
	{
		$new_node = new MyStack($element);
		if ($new_node != null)
		{
			$new_node->next = $this->top;
			$this->top = $new_node;
		}
	}
	//Remove top element
	function pop()
	{
		if ($this->top == null)
		{
			return;
		}
		$temp = $this->top;
		$this->top = $temp->next;
		$temp = null;
	}
	//Function which is display the path from root to leaf 
	function print_path($temp)
	{
		if ($temp != null)
		{
			$this->print_path($temp->next);
			echo " ". $temp->element->data ." ";
		}
	}
	//This function are collect path information using stack and when get leaf node then displaying node value
	function show_path($root)
	{
		if ($root != null)
		{
			//Add a new element into Stack
			$this->push($root);
			$this->show_path($root->left);
			$this->show_path($root->right);
			if ($root->left == null && $root->right == null)
			{
				echo "\n[";
				$this->print_path($this->top);
				echo " ]\n";
			}
			$this->pop();
		}
	}
}

function main()
{
	$obj = new BinaryTree();
	/* Make A Binary Tree
			-----------------------
			        1
			       /  \
			      2    3
			     /    /  \
			    4    5    6
			     \       / \
			      7     8   11
			           / \
			          9   10
			*/
	//Insert node into Binary tree
	//Insert node into Binary tree
	$obj->root = new Node(1);
	$obj->root->left = new Node(2);
	$obj->root->right = new Node(3);
	$obj->root->right->right = new Node(6);
	$obj->root->right->left = new Node(5);
	$obj->root->left->left = new Node(4);
	$obj->root->left->left->right = new Node(7);
	$obj->root->right->right->left = new Node(8);
	$obj->root->right->right->left->left = new Node(9);
	$obj->root->right->right->left->right = new Node(10);
	$obj->root->right->right->right = new Node(11);
	//Display root to all leaf path
	$obj->show_path($obj->root);
}
main();

Output

[ 1  2  4  7  ]

[ 1  3  5  ]

[ 1  3  6  8  9  ]

[ 1  3  6  8  10  ]

[ 1  3  6  11  ]
/*
  Node Js Program
  Print all paths from root node to leaf
*/
//Tree node
class Node
{
	//Set initial value of Binary Tree Node
	constructor(data)
	{
		this.data = data;
		this.left = null;
		this.right = null;
	}
}
//Define the custom stack class
class MyStack
{
	constructor(element)
	{
		this.element = element;
		this.next = null;
	}
}
class BinaryTree
{
	constructor()
	{
		this.top = null;
		this.root = null;
	}
	//add element into top of stack
	push(element)
	{
		var new_node = new MyStack(element);
		if (new_node != null)
		{
			new_node.next = this.top;
			this.top = new_node;
		}
	}
	//Remove top element
	pop()
	{
		if (this.top == null)
		{
			return;
		}
		var temp = this.top;
		this.top = temp.next;
		temp = null;
	}
	//Function which is display the path from root to leaf 
	print_path(temp)
	{
		if (temp != null)
		{
			this.print_path(temp.next);
			process.stdout.write(" " + temp.element.data + " ");
		}
	}
	//This function are collect path information using stack and when get leaf node then displaying node value
	show_path(root)
	{
		if (root != null)
		{
			//Add a new element into Stack
			this.push(root);
			this.show_path(root.left);
			this.show_path(root.right);
			if (root.left == null && root.right == null)
			{
				process.stdout.write("\n[");
				this.print_path(this.top);
				process.stdout.write(" ]\n");
			}
			this.pop();
		}
	}
}

function main()
{
	var obj = new BinaryTree();
	/* Make A Binary Tree
			-----------------------
			        1
			       /  \
			      2    3
			     /    /  \
			    4    5    6
			     \       / \
			      7     8   11
			           / \
			          9   10
			*/
	//Insert node into Binary tree
	//Insert node into Binary tree
	obj.root = new Node(1);
	obj.root.left = new Node(2);
	obj.root.right = new Node(3);
	obj.root.right.right = new Node(6);
	obj.root.right.left = new Node(5);
	obj.root.left.left = new Node(4);
	obj.root.left.left.right = new Node(7);
	obj.root.right.right.left = new Node(8);
	obj.root.right.right.left.left = new Node(9);
	obj.root.right.right.left.right = new Node(10);
	obj.root.right.right.right = new Node(11);
	//Display root to all leaf path
	obj.show_path(obj.root);
}
main();

Output

[ 1  2  4  7  ]

[ 1  3  5  ]

[ 1  3  6  8  9  ]

[ 1  3  6  8  10  ]

[ 1  3  6  11  ]
#   Python 3 Program
#   Print all paths from root node to leaf

# Tree node
class Node :
	
	# Set initial value of Binary Tree Node
	def __init__(self, data) :
		self.data = data
		self.left = None
		self.right = None
	

# Define the custom stack class
class MyStack :
	
	def __init__(self, element) :
		self.element = element
		self.next = None
	

class BinaryTree :
	
	def __init__(self) :
		self.top = None
		self.root = None
	
	# add element into top of stack
	def push(self, element) :
		new_node = MyStack(element)
		if (new_node != None) :
			new_node.next = self.top
			self.top = new_node
		
	
	# Remove top element
	def pop(self) :
		if (self.top == None) :
			# already empty
			return
		
		temp = self.top
		self.top = temp.next
		temp = None
	
	# Function which is display the path from root to leaf 
	def print_path(self, temp) :
		if (temp != None) :
			self.print_path(temp.next)
			print(" ", temp.element.data ," ", end = "")
		
	
	# This function are collect path information using stack and when get leaf node then displaying node value
	def show_path(self, root) :
		if (root != None) :
			# Add a new element into Stack
			self.push(root)
			self.show_path(root.left)
			self.show_path(root.right)
			if (root.left == None and root.right == None) :
				print("\n[", end = "")
				self.print_path(self.top)
				print(" ]\n", end = "")
			
			self.pop()
		
	

def main() :
	obj = BinaryTree()
	#  Make A Binary Tree
	# 		-----------------------
	# 		        1
	# 		       /  \
	# 		      2    3
	# 		     /    /  \
	# 		    4    5    6
	# 		     \       / \
	# 		      7     8   11
	# 		           / \
	# 		          9   10
	# 		
	
	# Insert node into Binary tree
	obj.root = Node(1)
	obj.root.left = Node(2)
	obj.root.right = Node(3)
	obj.root.right.right = Node(6)
	obj.root.right.left = Node(5)
	obj.root.left.left = Node(4)
	obj.root.left.left.right = Node(7)
	obj.root.right.right.left = Node(8)
	obj.root.right.right.left.left = Node(9)
	obj.root.right.right.left.right = Node(10)
	obj.root.right.right.right = Node(11)
	# Display root to all leaf path
	obj.show_path(obj.root)

if __name__ == "__main__": main()

Output

[  1    2    4    7   ]

[  1    3    5   ]

[  1    3    6    8    9   ]

[  1    3    6    8    10   ]

[  1    3    6    11   ]
#   Ruby Program
#   Print all paths from root node to leaf

# Tree node
class Node 

	# Define the accessor and reader of class Node  
	attr_reader :data, :left, :right
	attr_accessor :data, :left, :right


	
	# Set initial value of Binary Tree Node
	def initialize(data)
	
		self.data = data
		self.left = nil
		self.right = nil
	end
end
# Define the custom stack class
class MyStack 

	# Define the accessor and reader of class MyStack  
	attr_reader :element, :next
	attr_accessor :element, :next


	
	def initialize(element)
	
		self.element = element
		self.next = nil
	end
end
class BinaryTree 

	# Define the accessor and reader of class BinaryTree  
	attr_reader :top, :root
	attr_accessor :top, :root


	
	def initialize()
	
		self.top = nil
		self.root = nil
	end
	# add element into top of stack
	def push(element)
	
		new_node = MyStack.new(element)
		if (new_node != nil)
		
			new_node.next = self.top
			self.top = new_node
		end
	end
	# Remove top element
	def pop()
	
		if (self.top == nil)
		
			# already empty
			return
		end
		temp = self.top
		self.top = temp.next
		temp = nil
	end
	# Function which is display the path from root to leaf 
	def print_path(temp)
	
		if (temp != nil)
		
			self.print_path(temp.next)
			print(" ", temp.element.data ," ")
		end
	end
	# This function are collect path information using stack and when get leaf node then displaying node value
	def show_path(root)
	
		if (root != nil)
		
			# Add a new element into Stack
			self.push(root)
			self.show_path(root.left)
			self.show_path(root.right)
			if (root.left == nil && root.right == nil)
			
				print("\n[")
				self.print_path(self.top)
				print(" ]\n")
			end
			self.pop()
		end
	end
end
def main()

	obj = BinaryTree.new()
	#  Make A Binary Tree
	# 		-----------------------
	# 		        1
	# 		       /  \
	# 		      2    3
	# 		     /    /  \
	# 		    4    5    6
	# 		     \       / \
	# 		      7     8   11
	# 		           / \
	# 		          9   10
	# 		
	
	# Insert node into Binary tree
	obj.root = Node.new(1)
	obj.root.left = Node.new(2)
	obj.root.right = Node.new(3)
	obj.root.right.right = Node.new(6)
	obj.root.right.left = Node.new(5)
	obj.root.left.left = Node.new(4)
	obj.root.left.left.right = Node.new(7)
	obj.root.right.right.left = Node.new(8)
	obj.root.right.right.left.left = Node.new(9)
	obj.root.right.right.left.right = Node.new(10)
	obj.root.right.right.right = Node.new(11)
	# Display root to all leaf path
	obj.show_path(obj.root)
end
main()

Output

[ 1  2  4  7  ]

[ 1  3  5  ]

[ 1  3  6  8  9  ]

[ 1  3  6  8  10  ]

[ 1  3  6  11  ]
/*
  Scala Program
  Print all paths from root node to leaf
*/
//Tree node
class Node(var data: Int,
	var left: Node,
		var right: Node)
{
	//Set initial value of Binary Tree Node
	def this(data: Int)
	{
		this(data,null,null);
	}
}
//Define the custom stack class
class MyStack(var element: Node,
	var next: MyStack)
{
	def this(element: Node)
	{
		this(element,null);
	}
}
class BinaryTree(var top: MyStack,
	var root: Node)
{
	def this()
	{
		this(null,null);
	}
	//add element into top of stack
	def push(element: Node): Unit = {
		var new_node: MyStack = new MyStack(element);
		if (new_node != null)
		{
			new_node.next = this.top;
			this.top = new_node;
		}
	}
	//Remove top element
	def pop(): Unit = {
		if (this.top == null)
		{
			return;
		}
		var temp: MyStack = this.top;
		this.top = temp.next;
		temp = null;
	}
	//Function which is display the path from root to leaf 
	def print_path(temp: MyStack): Unit = {
		if (temp != null)
		{
			print_path(temp.next);
			print(" " + temp.element.data + " ");
		}
	}
	//This function are collect path information using stack and when get leaf node then displaying node value
	def show_path(root: Node): Unit = {
		if (root != null)
		{
			//Add a new element into Stack
			this.push(root);
			this.show_path(root.left);
			this.show_path(root.right);
			if (root.left == null && root.right == null)
			{
				print("\n[");
				this.print_path(this.top);
				print(" ]\n");
			}
			this.pop();
		}
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var obj: BinaryTree = new BinaryTree();
		/* Make A Binary Tree
				-----------------------
				        1
				       /  \
				      2    3
				     /    /  \
				    4    5    6
				     \       / \
				      7     8   11
				           / \
				          9   10
				*/
		//Insert node into Binary tree
		//Insert node into Binary tree
		obj.root = new Node(1);
		obj.root.left = new Node(2);
		obj.root.right = new Node(3);
		obj.root.right.right = new Node(6);
		obj.root.right.left = new Node(5);
		obj.root.left.left = new Node(4);
		obj.root.left.left.right = new Node(7);
		obj.root.right.right.left = new Node(8);
		obj.root.right.right.left.left = new Node(9);
		obj.root.right.right.left.right = new Node(10);
		obj.root.right.right.right = new Node(11);
		//Display root to all leaf path
		obj.show_path(obj.root);
	}
}

Output

[ 1  2  4  7  ]

[ 1  3  5  ]

[ 1  3  6  8  9  ]

[ 1  3  6  8  10  ]

[ 1  3  6  11  ]
/*
  Swift Program
  Print all paths from root node to leaf
*/
//Tree node
class Node
{
	var data: Int;
	var left: Node? ;
	var right: Node? ;
	//Set initial value of Binary Tree Node
	init(_ data: Int)
	{
		self.data = data;
		self.left = nil;
		self.right = nil;
	}
}
//Define the custom stack class
class MyStack
{
	var element: Node? ;
	var next: MyStack? ;
	init(_ element: Node? )
	{
		self.element = element;
		self.next = nil;
	}
}
class BinaryTree
{
	var top: MyStack? ;
	var root: Node? ;
	init()
	{
		self.top = nil;
		self.root = nil;
	}
	//add element into top of stack
	func push(_ element: Node? )
	{
		let new_node: MyStack? = MyStack(element);
		if (new_node != nil)
		{
			new_node!.next = self.top;
			self.top = new_node;
		}
	}
	//Remove top element
	func pop()
	{
		if (self.top == nil)
		{
			//already empty
			return;
		}
		var temp: MyStack? = self.top;
		self.top = temp!.next;
		temp = nil;
	}
	//Function which is display the path from root to leaf 
	func print_path(_ temp: MyStack? )
	{
		if (temp != nil)
		{
			self.print_path(temp!.next);
			print(" ", temp!.element!.data ," ", terminator: "");
		}
	}
	//This function are collect path information using stack and when get leaf node then displaying node value
	func show_path(_ root: Node? )
	{
		if (root != nil)
		{
			//Add a new element into Stack
			self.push(root);
			self.show_path(root!.left);
			self.show_path(root!.right);
			if (root!.left == nil && root!.right == nil)
			{
				print("\n[", terminator: "");
				self.print_path(self.top);
				print(" ]\n", terminator: "");
			}
			self.pop();
		}
	}
}
func main()
{
	let obj: BinaryTree = BinaryTree();
	/* Make A Binary Tree
			-----------------------
			        1
			       /  \
			      2    3
			     /    /  \
			    4    5    6
			     \       / \
			      7     8   11
			           / \
			          9   10
			*/
	//Insert node into Binary tree
	obj.root = Node(1);
	obj.root!.left = Node(2);
	obj.root!.right = Node(3);
	obj.root!.right!.right = Node(6);
	obj.root!.right!.left = Node(5);
	obj.root!.left!.left = Node(4);
	obj.root!.left!.left!.right = Node(7);
	obj.root!.right!.right!.left = Node(8);
	obj.root!.right!.right!.left!.left = Node(9);
	obj.root!.right!.right!.left!.right = Node(10);
	obj.root!.right!.right!.right = Node(11);
	//Display root to all leaf path
	obj.show_path(obj.root);
}
main();

Output

[  1    2    4    7   ]

[  1    3    5   ]

[  1    3    6    8    9   ]

[  1    3    6    8    10   ]

[  1    3    6    11   ]

Time Complexity Analysis

The time complexity of the show_path function is O(n), where n is the number of nodes in the binary tree. Each node is visited once during the depth-first search traversal.

Output Explanation

The output shows all the paths from the root node to each leaf node. For the example tree provided in the code, the output displays the paths as follows:

[  1  2  4  7 ]
    [  1  3  5 ]
    [  1  3  6  8  9 ]
    [  1  3  6  8  10 ]
    [  1  3  6  11 ]

Each line represents a path from the root node to a leaf node in the binary tree. The numbers within square brackets represent the nodes along the path.





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