865.Smallest Subtree with all the Deepest Nodes
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* subtreeWithAllDeepest(TreeNode* root) {
int DL= depth(root->left);
int DR = depth(root->right);
if (DL == DR)
return root;
else
return DL>DR? subtreeWithAllDeepest(root->left):subtreeWithAllDeepest(root->right);
}
private:
int depth(TreeNode* root)
{
if(root==NULL)
return 0;
int dl = depth(root->left);
int dr = depth(root->right);
return dl>dr ? dl+1:dr+1;
}
};Last updated