Category Archives: Trees

Find Count of Single Valued Subtrees

Given a binary tree, write a program to count the number of Single Valued Subtrees. A Single Valued Subtree is one in which all the nodes have same value. Expected time complexity is O(n). Example: Input: root of below tree 5 / \ 1 5 / \ \ 5 5 5 Output: 4 There are… Read More »

Mirror of n-ary Tree

Given a Tree where every node contains variable number of children, convert the tree to its mirror. Below diagram shows an example. We strongly recommend you to minimize your browser and try this yourself first. Node of tree is represented as a key and a variable sized array of children pointers. The idea is similar… Read More »

Succinct Encoding of Binary Tree

A succinct encoding of Binary Tree takes close to minimum possible space. The number of structurally different binary trees on n nodes is n’th Catalan number. For large n, this is about 4n; thus we need at least about log2 4 n = 2n bits to encode it. A succinct binary tree therefore would occupy… Read More »

Find Minimum Depth of a Binary Tree

Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from root node down to the nearest leaf node. For example, minimum height of below Binary Tree is 2. Note that the path must end on a leaf node. For example, minimum height of below… Read More »

Expression Tree

Expression tree is a binary tree in which each internal node corresponds to operator and each leaf node corresponds to operand so for example expression tree for 3 + ((5+9)*2) would be:

Diagonal Sum of a Binary Tree

Consider lines of slope -1 passing between nodes (dotted lines in below diagram). Diagonal sum in a binary tree is sum of all node’s data lying between these lines.