Category Archives: Trees

Calculate depth of a full Binary tree from Preorder

Given preorder of a binary tree, calculate its depth(or height) [starting from depth 0]. The preorder is given as a string with two possible characters. ‘l’ denotes the leaf ‘n’ denotes internal node The given tree can be seen as a full binary tree where every node has 0 or two children. The two children… Read More »

Subtree with given sum in a Binary Tree

You are given a binary tree and a given sum. The task is to check if there exist a subtree whose sum of all nodes is equal to the given sum. Examples: // For above tree Input : sum = 22 Output: “Yes” // sum of all nodes of subtree {1, 7, 12, 2} =… Read More »

Print all nodes in a binary tree having K leaves

Given a binary tree and a integer value K, the task is to find all nodes in given binary tree having K leaves in subtree rooted with them. Examples: // For above binary tree Input : k = 2 Output: {5, 7} // here node 5 and 7 have k = 2 leaves Input :… Read More »

Find maximum level sum in Binary Tree

Given a Binary Tree having positive and negative nodes, the task is to find maximum sum level in it. Examples: Input : 4 / \ 2 -5 / \ /\ -1 3 -2 6 Output: 6 Explanation : Sum of all nodes of 0’th level is 4 Sum of all nodes of 1’th level is… Read More »

Continuous Tree

A tree is Continuous tree if in each root to leaf path, absolute difference between keys of two adjacent is 1. We are given a binary tree, we need to check if tree is continuous or not. Examples: Input : 3 / \ 2 4 / \ \ 1 3 5 Output: “Yes” // 3->2->1… Read More »