Problem statement: Given a binary tree, find the length of the longest consecutive sequence path. The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive… Continue Reading
Problem: Calculate sum of all the leaf nodes in binary tree. Logic: In this implementation we are passing 0 as initial result. When node is a leaf node(left child and right child is null) we are assigning node value to… Continue Reading
Problem: Calculate height of a binary tree: Logic: In binary tree left subtree and right subtree are also binary trees. We will calculate height of each subtree and will select maximum of both. 1 is added to maximum height of… Continue Reading
Problem: Calculate sum of all nodes in a binary tree.
int SumOfNodes(Node rt)
if (rt == null)
return rt.value + SumOfNodes(rt.left) + SumOfNodes(rt.right);
You refer following image to understand function calls in above recursive method. We need to visit all nodes, so time complexity will be O( n)