Smallest Subtree with all the Deepest Nodes in C++

C++Server Side ProgrammingProgramming

Suppose we have a binary tree rooted at root, the depth of each node is the shortest distance to the root. Here a node is deepest if it has the largest depth possible among any node in the entire tree. The subtree of a node is that node, plus the set of all descendants of that node. We have to find the node with the largest depth such that it contains all the deepest nodes in its subtree. So if the tree is like −

Then the deepest subtree will be −

To solve this, we will follow these steps −

  • Define a method called solve(), this will take root as input

  • if root is null, then return (null, 0)

  • l := solve(left of root), r := solve(right of root)

  • if second value of left > second value of r, then return a pair (first of l, 1 + second of l)

  • otherwise when second value of left < second value of r, then return a pair (first of r and 1 + second of r)

  • return a pair(root, second of l + 1)

  • From the main method call solve(root), and return the second value of it


Let us see the following implementation to get better understanding −

class Solution {
   pair <TreeNode*, int> solve(TreeNode* root){
      if(!root) return {NULL, 0};
      pair <TreeNode*, int> L = solve(root->left);
      pair <TreeNode*, int> R = solve(root->right);
      if(L.second > R.second)return {L.first, L.second + 1};
      else if(L.second < R.second) return {R.first, R.second + 1};
      return {root, L.second + 1};
   TreeNode* subtreeWithAllDeepest(TreeNode* root) {
      return solve(root).first;




Published on 17-Mar-2020 06:24:06