LeetCode每日一题 1123. 最深叶节点的最近公共祖先

题解:查找二叉树中最深叶节点的最近公共祖先

这个问题要求我们找到给定二叉树中最深叶节点的最近公共祖先。我们可以使用递归的方式来解决这个问题。

算法思路

此代码用到两个辅助函数来完成任务:findDeepestLeavesfindCommonAncestor

  1. findDeepestLeaves 函数用于递归查找二叉树中的最深叶节点。在遍历二叉树的过程中,我们维护一个 maxDepth 变量来记录当前已找到的最大深度,并使用 deepestLeaves 向量来存储最深的叶节点。

  2. findCommonAncestor 函数用于查找最深叶节点的最近公共祖先。在该函数中,我们首先检查当前节点是否包含在 deepestLeaves 中,如果是,则返回该节点作为最近公共祖先。如果不是,我们递归查找左子树和右子树的最近公共祖先,并根据左右子树的结果来决定返回哪个节点。

最后,在主函数 lcaDeepestLeaves 中,我们首先调用 findDeepestLeaves 函数来找到最深的叶节点,并将它们存储在 deepestLeaves 向量中。然后,我们调用 findCommonAncestor 函数来查找最近公共祖先,并返回结果。

代码实现

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

class Solution {
public:
    TreeNode* lcaDeepestLeaves(TreeNode* root) {
        int maxDepth = 0;
        vector<TreeNode*> deepestLeaves;
        findDeepestLeaves(root, 0, maxDepth, deepestLeaves);
        return findCommonAncestor(root, deepestLeaves);
    }

private:
    void findDeepestLeaves(TreeNode* root, int depth, int& maxDepth, vector<TreeNode*>& deepestLeaves) {
        if (!root) {
            return;
        }

        if (depth > maxDepth) {
            deepestLeaves.clear();
            deepestLeaves.push_back(root);
            maxDepth = depth;
        } else if (depth == maxDepth) {
            deepestLeaves.push_back(root);
        }

        findDeepestLeaves(root->left, depth + 1, maxDepth, deepestLeaves);
        findDeepestLeaves(root->right, depth + 1, maxDepth, deepestLeaves);
    }

    TreeNode* findCommonAncestor(TreeNode* root, vector<TreeNode*>& nodes) {
        if (!root || nodes.empty()) {
            return nullptr;
        }

        if (find(nodes.begin(), nodes.end(), root) != nodes.end()) {
            return root;
        }

        TreeNode* left = findCommonAncestor(root->left, nodes);
        TreeNode* right = findCommonAncestor(root->right, nodes);

        if (left && right) {
            return root;
        } else if (left) {
            return left;
        } else {
            return right;
        }
    }
};

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值