LCA of the Deepest Nodes

Given a tree, find the smallest subtree that contains all of the tree's deepest tree

Thoughts

分治, 递归统计每个子节点的深度, 当最深深度只出现一次时, 把那个子节点所对应的return直接返回(并深度加一), 当出现超过一次时, 说明任何子树都不包含包括所有deepest node的lca, 直接返回root.

Code

/**
 * 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) {
        return helper(root, 0).first;
    }

private:
    pair<TreeNode*, int> helper(TreeNode* root, int depth) {
        if (!root) return {NULL, 0};
        const auto left = helper(root->left, depth + 1);
        const auto right = helper(root->right, depth + 1);
        if (left.second > right.second) {
            return left;
        } else if (right.second > left.second) {
            return right;
        } else {
            return {root, max(left.second, depth)};
        }
    }
};

Last updated

Was this helpful?