Data Structures Tutorial

Data Structures Tutorial Asymptotic Notation Structure and Union Array Data Structure Linked list Data Structure Type of Linked list Advantages and Disadvantages of linked list Queue Data Structure Implementation of Queue Stack Data Structure Implementation of Stack Sorting Insertion sort Quick sort Selection sort Heap sort Merge sort Bucket sort Count sort Radix sort Shell sort Tree Traversal of the binary tree Binary search tree Graph Spanning tree Linear Search Binary Search Hashing Collision Resolution Techniques

Misc Topic:

Priority Queue in Data Structure Deque in Data Structure Difference Between Linear And Non Linear Data Structures Queue Operations In Data Structure About Data Structures Data Structures Algorithms Types of Data Structures Big O Notations Introduction to Arrays Introduction to 1D-Arrays Operations on 1D-Arrays Introduction to 2D-Arrays Operations on 2D-Arrays Strings in Data Structures String Operations Application of 2D array Bubble Sort Insertion Sort Sorting Algorithms What is DFS Algorithm What Is Graph Data Structure What is the difference between Tree and Graph What is the difference between DFS and BFS Bucket Sort Dijkstra’s vs Bellman-Ford Algorithm Linear Queue Data Structure in C Stack Using Array Stack Using Linked List Recursion in Fibonacci Stack vs Array What is Skewed Binary Tree Primitive Data Structure in C Dynamic memory allocation of structure in C Application of Stack in Data Structures Binary Tree in Data Structures Heap Data Structure Recursion - Factorial and Fibonacci What is B tree what is B+ tree Huffman tree in Data Structures Insertion Sort vs Bubble Sort Adding one to the number represented an array of digits Bitwise Operators and their Important Tricks Blowfish algorithm Bubble Sort vs Selection Sort Hashing and its Applications Heap Sort vs Merge Sort Insertion Sort vs Selection Sort Merge Conflicts and ways to handle them Difference between Stack and Queue AVL tree in data structure c++ Bubble sort algorithm using Javascript Buffer overflow attack with examples Find out the area between two concentric circles Lowest common ancestor in a binary search tree Number of visible boxes putting one inside another Program to calculate the area of the circumcircle of an equilateral triangle Red-black Tree in Data Structures Strictly binary tree in Data Structures 2-3 Trees and Basic Operations on them Asynchronous advantage actor-critic (A3C) Algorithm Bubble Sort vs Heap Sort Digital Search Tree in Data Structures Minimum Spanning Tree Permutation Sort or Bogo Sort Quick Sort vs Merge Sort Boruvkas algorithm Bubble Sort vs Quick Sort Common Operations on various Data Structures Detect and Remove Loop in a Linked List How to Start Learning DSA Print kth least significant bit number Why is Binary Heap Preferred over BST for Priority Queue Bin Packing Problem Binary Tree Inorder Traversal Burning binary tree Equal Sum What is a Threaded Binary Tree? What is a full Binary Tree? Bubble Sort vs Merge Sort B+ Tree Program in Q language Deletion Operation from A B Tree Deletion Operation of the binary search tree in C++ language Does Overloading Work with Inheritance Balanced Binary Tree Binary tree deletion Binary tree insertion Cocktail Sort Comb Sort FIFO approach Operations of B Tree in C++ Language Recaman’s Sequence Tim Sort Understanding Data Processing Applications of trees in data structures Binary Tree Implementation Using Arrays Convert a Binary Tree into a Binary Search Tree Create a binary search tree Horizontal and Vertical Scaling Invert binary tree LCA of binary tree Linked List Representation of Binary Tree Optimal binary search tree in DSA Serialize and Deserialize a Binary Tree Tree terminology in Data structures Vertical Order Traversal of Binary Tree What is a Height-Balanced Tree in Data Structure Convert binary tree to a doubly linked list Fundamental of Algorithms Introduction and Implementation of Bloom Filter Optimal binary search tree using dynamic programming Right side view of binary tree Symmetric binary tree Trim a binary search tree What is a Sparse Matrix in Data Structure What is a Tree in Terms of a Graph What is the Use of Segment Trees in Data Structure What Should We Learn First Trees or Graphs in Data Structures All About Minimum Cost Spanning Trees in Data Structure Convert Binary Tree into a Threaded Binary Tree Difference between Structured and Object-Oriented Analysis FLEX (Fast Lexical Analyzer Generator) Object-Oriented Analysis and Design Sum of Nodes in a Binary Tree What are the types of Trees in Data Structure What is a 2-3 Tree in Data Structure What is a Spanning Tree in Data Structure What is an AVL Tree in Data Structure Given a Binary Tree, Check if it's balanced B Tree in Data Structure Convert Sorted List to Binary Search Tree Flattening a Linked List Given a Perfect Binary Tree, Reverse Alternate Levels Left View of Binary Tree What are Forest Trees in Data Structure Compare Balanced Binary Tree and Complete Binary Tree Diameter of a Binary Tree Given a Binary Tree Check the Zig Zag Traversal Given a Binary Tree Print the Shortest Path Given a Binary Tree Return All Root To Leaf Paths Given a Binary Tree Swap Nodes at K Height Given a Binary Tree Find Its Minimum Depth Given a Binary Tree Print the Pre Order Traversal in Recursive Given a Generate all Structurally Unique Binary Search Trees Perfect Binary Tree Threaded Binary Trees Function to Create a Copy of Binary Search Tree Function to Delete a Leaf Node from a Binary Tree Function to Insert a Node in a Binary Search Tree Given Two Binary Trees, Check if it is Symmetric A Full Binary Tree with n Nodes Applications of Different Linked Lists in Data Structure B+ Tree in Data Structure Construction of B tree in Data Structure Difference between B-tree and Binary Tree Finding Rank in a Binary Search Tree Finding the Maximum Element in a Binary Tree Finding the Minimum and Maximum Value of a Binary Tree Finding the Sum of All Paths in a Binary Tree Time Complexity of Selection Sort in Data Structure How to get Better in Data Structures and Algorithms Binary Tree Leaf Nodes Classification of Data Structure Difference between Static and Dynamic Data Structure Find the Union and Intersection of the Binary Search Tree Find the Vertical Next in a Binary Tree Finding a Deadlock in a Binary Search Tree Finding all Node of k Distance in a Binary Tree Finding Diagonal Sum in a Binary Tree Finding Diagonal Traversal of The Binary Tree Finding In-Order Successor Binary Tree Finding the gcd of Each Sibling of the Binary Tree Greedy Algorithm in Data Structure How to Calculate Space Complexity in Data Structure How to find missing numbers in an Array Kth Ancestor Node of Binary Tree Minimum Depth Binary Tree Mirror Binary Tree in Data Structure Red-Black Tree Insertion Binary Tree to Mirror Image in Data Structure Calculating the Height of a Binary Search Tree in Data Structure Characteristics of Binary Tree in Data Structure Create a Complete Binary Tree from its Linked List Field in Tree Data Structure Find a Specified Element in a binary Search Tree Find Descendant in Tree Data Structure Find Siblings in a Binary Tree Given as an Array Find the Height of a Node in a Binary Tree Find the Second-Largest Element in a Binary Tree Find the Successor Predecessor of a Binary Search Tree Forest of a Tree in Data Structure In Order Traversal of Threaded Binary Tree Introduction to Huffman Coding Limitations of a Binary Search Tree Link State Routing Algorithm in Data Structure Map Reduce Algorithm for Binary Search Tree in Data Structure Non-Binary Tree in Data Structure Quadratic Probing Example in Hashing Scope and Lifetime of Variables in Data Structure Separate Chaining in Data Structure What is Dynamic Data Structure Separate Chaining vs Open Addressing Time and Space Complexity of Linear Data Structures Abstract Data Types in Data Structures Binary Tree to Single Linked List Count the Number of Nodes in the Binary Tree Count Total No. of Ancestors in a Binary Search Tree Elements of Dynamic Programming in Data Structures Find cost of tree with prims algorithm in data structures Find Preorder Successor in a Threaded Binary Tree Find Prime Nodes Sum Count in Non-Binary Tree Find the Right Sibling of a Binary Tree with Parent Pointers Find the Width of the Binary Search Tree Forest trees in Data Structures Free Tree in Data Structures Frequently asked questions in Tree Data Structures Infix, Postfix and Prefix Conversion Time Complexity of Fibonacci Series What is Weighted Graph in Data Structure What is the Advantage of Linear Search?

Finding the Sum of All Paths in a Binary Tree

Implementation

// Writing the C++ program to implement the below approach. 
#include <bits/stdc++.h>
using namespace std;


// creating the new tree node structure.
struct Tree__nod {
	int val;
	Tree__nod *Lft, *Rt;
};


// creating a new function that will help us create a new node for the tree with a given value. 
struct Tree__nod* add__nod(int record)
{
	// We have to provide the new memory for the tree.
	struct Tree__nod* __nod
		= (struct Tree__nod*)malloc(
			sizeof(struct Tree__nod));


	// we will allocate the new record to the ‘val’ variable.
	__nod->val = record;
	__nod->Lft = NILL;
	__nod->Rt = NILL;
	return __nod;
};


// creating a new function that will eventually help us create the leaf path sum of the binary tree using the DFS method.
void dfs(Tree__nod* root, int sum,
		vector<int>& paths)
{
	// if the node has the NULL value, we must return the same.
	if (root == NILL)
		return;


	// we have to add the value of the node to the sum of the path and then observe 
	sum += root->val;


	// we have to keep the sum of the path in storage if the node turns out to be a leaf node. 
	if (root->Lft == NILL
		and root->Rt == NILL) {


		pathSum.push_back(sum);
		return;
	}


	// we have to move to the left child.
	dfs(root->Lft, sum, pathSum);


	// we have to move to the right child.
	dfs(root->Rt, sum, pathSum);
}


// creating a new function that will eventually check the path sum of the root to a leaf of a binary tree. 
void findPathSum(Tree__nod* root)
{
	// we have to store the sum of the path
	vector<int> pathSum;


	// we have to call the dfs function
	dfs(root, 0, pathSum);


	// we have to print the sum of the path
	for (int num: pathSum) {
		cout << num << " ";
	}
	cout << endl;
}


// writing the main code
int main()
{
	// We can see a binary tree in the code stated below:
	Tree__nod* root = add__nod(30);
	root->Lft = add__nod(10);
	root->Rt = add__nod(50);
	root->Lft->Lft = add__nod(3);
	root->Lft->Rt = add__nod(16);
	root->Rt->Lft = add__nod(40);
	root->Rt->Rt = add__nod(60);


	/* The above code constructs this tree


				30
			/	 \
		10	 50
		/ \	 / \
		3 16 40 60
*/


	// Function Call
	findPathSum(root);


	return 0;
}

Output:

Finding the Sum of All Paths in a Binary Tree

Example 2)

// Writing the C# program to implement the below approach. 
using System;
using System.Collections.Generic;
// creating the new tree node structure.
public class __nod
{
	public int val;
	public __nod Lft, Rt;
	public __nod(int item)
	{
		val = item;
		Lft = Rt = NILL;
	}
}
public class BinaryTree
{
	public static __nod __nod;
// creating a new function that will help us create a new node for the tree with a given value. 
	static void dfs(__nod root, int sum, List<int> pathSum)
	{
	// if the node has the NULL value, we must return the same. 
		if (root == NILL)
		{
			return;
		}
// we have to add the value of the node to the sum of the path and then observe 
		sum += root.val;
	// we have to keep the sum of the path in storage if the node turns out to be a leaf node. 
		if(root.Lft == NILL && root.Rt == NILL)
		{
			pathSum.Add(sum);
			return;
		}
	// we have to move to the left child.
		dfs(root.Lft, sum, pathSum);
	// we have to move to the right child.
		dfs(root.Rt, sum, pathSum);
	}


	// creating a new function that will eventually check the path sum of the root to a leaf of a binary tree. 
	static void findPathSum(__nod root)
	{
	// we have to store the sum of the path
		List<int> pathSum = new List<int>();
	// we have to call the dfs function
		dfs(root, 0, pathSum);
		// we have to print the sum of the path
		foreach(int num in pathSum)
		{
			Console.Write(num + " ");
		}
	}
// writing the main code
	static public void Main ()
	{
	
		// Construct binary tree
		BinaryTree.__nod = nw __nod(30);
		BinaryTree.__nod.Lft = nw __nod(10);
		BinaryTree.__nod.Rt = nw __nod(50);
		BinaryTree.__nod.Lft.Lft = nw __nod(3);
		BinaryTree.__nod.Lft.Rt = nw __nod(16);
		BinaryTree.__nod.Rt.Lft = nw __nod(40);
		BinaryTree.__nod.Rt.Rt = nw __nod(60);
		
	/* The above code constructs this tree


			30
		/	 \
	10	 50
	/ \	 / \
	3 16 40 60
*/
		// Function call
		findPathSum(__nod);
	}
}

Output:

Finding the Sum of All Paths in a Binary Tree

Example 3)

// Writing the Java program to implement the below approach. 
import java.util.*;


class TFT{
// creating the new tree node structure.
static class __nod
{
	int val;
	__nod Lft, Rt;
};
// creating a new function that will help us create a new node for the tree with a given value. 


static __nod nw__nod(int record)
{
	__nod temp = nw __nod();
	temp.val = record;
	temp.Lft = temp.Rt = NILL;
	return temp;
}
// We have to provide the new memory for the tree.
// we will allocate the new data to the ‘val’ variable.	
// creating a new function that will eventually help us create the leaf path sum of the binary tree using the DFS method.
static void dfs(__nod root, int sum,
				ArrayList<Integer> pathSum)
{
// if the node has the NULL value, we must return the same.
	if (root == NILL)
		return;
// we have to add the value of the node to the sum of the path and then observe 
	sum += root.val;
// we have to keep the sum of the path in storage if the node turns out to be a leaf node. 
	if (root.Lft == NILL &&
	root.Rt == NILL)
	{
		pathSum.add(sum);
		return;
	}
// we have to move to the left child.
	dfs(root.Lft, sum, pathSum);
	// we have to move to the right child.
	dfs(root.Rt, sum, pathSum);
}


// creating a new function that will eventually check the path sum of the root to a leaf of a binary tree. 
static void findPathSum(__nod root)
{
	// we have to store the sum of the path
	ArrayList<Integer> pathSum = new ArrayList<>();
// we have to call the dfs function
	dfs(root, 0, pathSum);
// we have to print the sum of the path
	for(int num : pathSum)
	{
		System.out.print(num + " ");
	}
}
// writing the main code	
public static void main(String[] args)
{
	
	// Construct binary tree
	__nod root = nw__nod(30);
	root.Lft = nw__nod(10);
	root.Rt = nw__nod(50);
	root.Lft.Lft = nw__nod(3);
	root.Lft.Rt = nw__nod(16);
	root.Rt.Lft = nw__nod(40);
	root.Rt.Rt = nw__nod(60);


	/* The above code constructs this tree


			30
		/	 \
	10	 50
	/ \	 / \
	3 16 40 60
*/


	// Function call
	findPathSum(root);
}
}

Output:

Finding the Sum of All Paths in a Binary Tree

Example 4)

# Writing the Python program to implement the below approach. 


from collections import deque


# creating the new tree node structure.
class __nod:


	def __init__(self, x):
	
		self.record = x
		self.Lft = None
		self.Rt = None
		
pathSum = []


# creating a new function that will help us create a new node for the tree with a given value. 
def dfs(root, sum):


	# if the node has the NULL value, we have to return the same.
	if (root == None):
		return


	# we have to add the node's value to the sum of the path and then observe 
	sum += root.record


	# we have to keep the sum of the path in storage if the node turns out to be a leaf node. 
	If (root.Lft == None and
		root.Rt == None):
		pathSum.append(sum)
		return


	# we have to move to the left child.
	dfs(root.Lft, sum)


	# we have to move to the right child.
	dfs(root.Rt, sum)


# Creating a new function that will eventually check the path sum of the root to a leaf of a binary tree. 


def findPathSum(root):


	# we have to store the sum of the path
	# vector<int> pathSum


	#  We have to call the dfs function
	dfs(root, 0)


	# We have to print the sum of the path
	for num in pathSum:
		print(num, end = " ")
		
# writing the main code
if __name__ == '__main__':


	# Given binary tree
	root = __nod(30)
	root.Lft = __nod(10)
	root.Rt = __nod(50)
	root.Lft.Lft = __nod(3)
	root.Lft.Rt = __nod(16)
	root.Rt.Lft = __nod(40)
	root.Rt.Rt = __nod(60)


# /* The above code constructs this tree
#
#			 30
#		 /	 \
#		 10	 50
#	 / \	 / \
#	 3 16 40 60
# */


	# Function Call
	findPathSum(root)

Output:

Finding the Sum of All Paths in a Binary Tree

Example 5)

<script>
// Writing the Javascript program to implement the below approach. 
// creating the new tree node structure.
class __nod
{
	constructor(record)
	{
		this.val=record;
		this.Lft=this.Rt=NILL;
	}
}
// creating a new function that will eventually help us create the leaf path sum of the binary tree using the DFS method.
function dfs(root,sum,pathSum)
{
// if the node has the NULL value, we must return the same.
	if (root == NILL)
		return;
// we have to add the value of the node to the sum of the path and then observe 
	sum += root.val;
// we have to keep the sum of the path in storage if the node turns out to be a leaf node. 
	if (root.Lft == NILL &&
	root.Rt == NILL)
	{
		pathSum.push(sum);
		return;
	}
// we have to move to the left child.
	dfs(root.Lft, sum, pathSum);
	// we have to move to the right child.
	dfs(root.Rt, sum, pathSum);
}
// creating a new function that will eventually check the path sum of the root to a leaf of a binary tree. 
function findPathSum(root)
{
		// we have to store the sum of the path
	let pathSum = [];
// we have to call the dfs function
	dfs(root, 0, pathSum);
	// we have to print the sum of the path
	for(let num=0;num<pathSum.length;num++)
	{
		document.write(pathSum[num] + " ");
	}
}


// writing the main code
	// We can see a binary tree in the code stated below:
let root = nw __nod(30);
root.Lft = nw __nod(10);
root.Rt = nw __nod(50);
root.Lft.Lft = nw __nod(3);
root.Lft.Rt = nw __nod(16);
root.Rt.Lft = nw __nod(40);
root.Rt.Rt = nw __nod(60);


/* The above code constructs this tree


			30
		/	 \
	10	 50
	/ \	 / \
	3 16 40 60
*/


// Function call
findPathSum(root);
</script>

Output:

Finding the Sum of All Paths in a Binary Tree

Example 6)

// writing a C++ program to implement the sum of all the paths in a given binary tree. 
#include <bits/stdc++.h>
using namespace std;


class __nod
{
	public:
	int record;
	__nod *Lft, *Rt;
};
// creating a new function that will help us create a new node for the tree with a given value. 
__nod* nw__nod(int record)
{
	__nod* __nod = nw __nod();
	__nod->record = record;
	__nod->Lft = __nod->Rt = NILL;
	return (__nod);
}


// the function used previously will return the sum to all leaf paths.
// the very first one is the root of the subtree which we are using currently, and the second one is the value of the number formed by all the nodes from the root to the brand new node. 
int treePathsSumUtil(__nod *root, int val)
{
	// aspecting the basic case
	if (root == NILL) return 0;


	// we have to modify the value
	val = (val*10 + root->record);


	// In case the current node of the given binary tree is a leaf, then we have to return the value which val. 
	if (root->Lft==NILL && root->Rt==NILL)
	return val;


	// we have to give back the recur values for the left and right subtree.
	return treePathsSumUtil(root->Lft, val) +
		treePathsSumUtil(root->Rt, val);
}


// A wrapper function over treePathsSumUtil()
int treePathsSum(__nod *root)
{
	// we have to give out the very first value as 0
	// as we know, there will be nothing above the root 
	return treePathsSumUtil(root, 0);
}


// writing the main code to implement the above functions.
int main()
{
	__nod *root = nw__nod(6);
	root->Lft = nw__nod(3);
	root->Rt = nw__nod(5);
	root->Lft->Lft = nw__nod(2);
	root->Lft->Rt = nw__nod(5);
	root->Rt->Rt = nw__nod(4);
	root->Lft->Rt->Lft = nw__nod(7);
	root->Lft->Rt->Rt = nw__nod(4);
	cout<<"Sum of all paths is "<<treePathsSum(root);
	return 0;
}

Output:

Finding the Sum of All Paths in a Binary Tree