- Related Questions & Answers
- Sum of the nodes of a Singly Linked List in C Program
- C++ Programming for Smallest K digit number divisible by X?
- Print n smallest elements from given array in their original order
- C++ Program for Smallest K digit number divisible by X?
- How to expand JTree row to display all the nodes and child nodes in Java
- Java Program to get the count of child nodes of any node in JTree
- How to get this nodes’s parent in a JTree with Java?
- Allow multiple selection of nodes not necessarily contigous in JTree
- How to get the leaves of nodes in a JTree with Java?
- How to check if two nodes are equal in a JTree with Java?
- Can we prevent the collapse of nodes and child nodes in a JTree with Java?
- How to allow contigous selection of nodes in a JTree?
- C++ Program to Find Whether a Path Exists Between 2 Given Nodes
- C++ Program to Find Second Smallest of n Elements with Given Complexity Constraint
- C++ Program to Find Path Between Two Nodes in a Graph

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 { public: 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; } };

[3,5,1,6,2,0,8,null,null,7,4]

[2,7,4]

Advertisements